<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="@android:color/holo_green_light"
android:orientation="vertical" > <TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text1"/> <TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text2"/>
</LinearLayout>
item_toast
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="toast1"
android:gravity="center"
android:text="自定义Toast" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="toast2"
android:gravity="center"
android:text="Toast.makeText" /> </LinearLayout>
activity_main
public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} public void toast1(View v){
//Toast通过构造方法创建,但是必须手动设置视图(setView、setDuration)
Toast toast = new Toast(this); //动态加载布局
View view = getLayoutInflater().inflate(R.layout.item_toast, null);
TextView tv1 = (TextView) view.findViewById(R.id.tv1);
TextView tv2 = (TextView) view.findViewById(R.id.tv2); //view.setBackgroundResource(R.drawable.ic_launcher);
view.setBackgroundColor(Color.YELLOW);;
tv1.setText("提示");
tv2.setText("再按一次退出"); toast.setView(view);
//Gravity.FILL_HORIZONTAL显示水平铺满,offset代表x,y轴上的偏移
toast.setGravity(Gravity.FILL_HORIZONTAL|Gravity.BOTTOM, 0, 500);
toast.setDuration(Toast.LENGTH_SHORT);
toast.show(); } public void toast2(View v){
Toast toast = Toast.makeText(this, "静态方法构建的Toast", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.LEFT, 0, 800);
//只有静态方法构建的toast才能用setText()方法
toast.setText("你好吗?");//打印你好吗?
toast.setText(R.string.hello_world);//打印的是Hello world!
toast.show();
} }
MainActivity