1.Toast的默认效果
Toast.makeText(getApplicationContext(), "这里输入你想弹出的提示文字", Toast.LENGTH_SHORT).show();
Toast.LENGTH_SHORT / Toast.LENGTH_LONG:这是显示时长,Toast.LENGTH_SHORT(短),Toast.LENGTH_LONG(长)。
2.定义Toast的显示位置
Toast toast = Toast.makeText(getApplicationContext(), "自定义位置", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
setGravity:设置显示位置。
3.带图片的Toast
Toast toast = Toast.makeText(getApplicationContext(), "带图片",
Toast.LENGTH_SHORT);
LinearLayout layout = (LinearLayout) toast.getView();
ImageView imgView = new ImageView(getApplicationContext());
imgView.setImageResource(R.drawable.ic_launcher);//设置图片
layout.addView(imgView, 0);
toast.show();
4.Toast的自定义
java代码:
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.toast,
(ViewGroup) findViewById(R.id.toast));
TextView text = (TextView) view.findViewById(R.id.textView1);
text.setText("自定义Toast");
toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(view);
toast.show();
toast.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/title2" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imageView1"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="10dp"
android:text="TextView" />
</RelativeLayout>