一、思路
1、要想用Toast同时显示多种VIEW(图片、文字等),使用Layout的XML文件打包好各个VIEW,或者使用代码编写好各个View的属性和包含关系。
2、要注意已经被其它LinearLayout对象添加过的VIEW,不能再添加进另一个LinearLayout对象的。
二、示例
1、编写需要以Toast方式显示的View的XML文件toast.xml,放置在res/layout下。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toastview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Toast测试" /> </LinearLayout>这个View只包含一个图片和一段文字。
2、创建Toast对象,调用里面的setView方法
public class ToastTestActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Toast toast = new Toast(getApplicationContext()); toast.setView(View.inflate(getApplicationContext(), R.layout.toast, null));//使用View的静态方法inflate()将XML转化为View; toast.setGravity(Gravity.TOP, 0, 100);//设置toast的显示位置; toast.setDuration(Toast.LENGTH_LONG);//设置显示的时间长度; toast.show();//调用shwo()将toast显示出来。 } }
三、总结
1、先编写好toast的显示的View的XML文件。
2、为toast对象设置好所有属性。
3、调用toast对象的shwo()方法,将toast显示出来。