2019独角兽企业重金招聘Python工程师标准>>>
废话不多说,直接上代码:
/**
* toast自带的设置图片类型的方法
*
* @param view
*/
public void btn1(View view) {
Toast toast = Toast.makeText(MainActivity.this, "带图片的toast", Toast.LENGTH_SHORT);
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.mipmap.ic_launcher);
toast.setGravity(Gravity.CENTER, 0, 0);//如果不加这个布局设置,图片就会显示在文字上面;
LinearLayout toastView = (LinearLayout) toast.getView();//先获取toast的布局对象
toastView.addView(imageView);//给布局对象添加view
toast.show();
}
效果如下:
设置toast的位置:
/**
* 设置toast显示位置
*
* @param view
*/
public void btn2(View view) {
Toast toast = Toast.makeText(getApplicationContext(), "lalala", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);//在这里有各种选项,看单词就知道什么意思了
toast.show();
}
//比较简单不贴图了
完全自定义的toast:
1. 布局文件 toast_define:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:background="@drawable/ab"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tv_title"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:background="#7030ff8f"
android:drawableLeft="@android:drawable/btn_star_big_on"
android:gravity="center"
android:text="自定义toast布局"
android:textSize="25sp" />
<ImageView
android:id="@+id/iv_content"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:background="#f9f9"
android:src="@android:drawable/sym_def_app_icon" />
<TextView
android:id="@+id/tv_content"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:background="#7031ffff"
android:gravity="center"
android:text="完全自定义的toast"
android:textSize="25sp" />
</LinearLayout>
2.代码部分:
/**
* 完全自定义的toast布局
*
* @param view
*/
public void btn3(View view) {
Toast toast = new Toast(this);
View toastView = LayoutInflater.from(this).inflate(R.layout.toast_define, null);
TextView content = (TextView) toastView.findViewById(R.id.tv_content);
content.setText("烦烦烦烦");
content.setTextColor(Color.parseColor("#ff0000"));
toast.setGravity(Gravity.TOP, 0, 0);
toast.setView(toastView);
toast.show();
}
显示效果:
比较丑,讲究看看吧;