一、Toast的简介
Toast是Android中用来显示显示信息的一种机制,和Dialog不一样的是,Toast是没有焦点的,而且Toast显示的时间有限,过一定的时间就会自动消失。
二、简单的Toast
Toast toast = Toast.makeText(getApplicationContext(), "我是一个Toast", Toast.LENGTH_SHORT);
Spanned spanned= Html.fromHtml("我是<img src=''/>一个<font color='#ff0000'>Toast</font>", new Html.ImageGetter() {
@Override
public Drawable getDrawable(String source) {
Drawable drawable=getResources().getDrawable(R.mipmap.ic_launcher);
drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
return drawable;
}
},null);
toast.setText(spanned);
toast.setGravity(Gravity.LEFT, 0, 0);
toast.show();
运行结果如下
三、自定义Toast
自定义Toast与简单Toast的区别就是弹出信息的布局是自己进行设置的,通过在layout中新建一个新的xml文件toast_item进行内容的布局。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textview_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000"/>
<ImageView
android:id="@+id/image_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"/>
<TextView
android:id="@+id/textview_toast2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="内容"/>
</LinearLayout>
2.要在MainActivity中新建一个适配器,将内容适配到自定义的item中
Toast toast2=new Toast(getApplicationContext());
LayoutInflater inflater=getLayoutInflater();
View toastView=inflater.inflate(R.layout.toast_item, null);
TextView textView_title= (TextView) toastView.findViewById(R.id.textview_toast);
textView_title.setText("我是一个自定义Toast");
toast2.setView(toastView);
toast2.setDuration(Toast.LENGTH_SHORT);
toast2.show();