原本以为Toast只有那么一个简单的功能,就是Toast.makeText(context, text, duration).show();这样就完了。
但是前几天发现一个问题就是不能在子线程中这么用,于是就看了看这个Toast的使用。发现Toast还可以自定义位置显示、带图片显示、当然还有在子线程中显示。
一个例子说明:
布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.toasttest.MainActivity" >
<Button
android:id="@+id/bt1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="默认" />
<Button
android:id="@+id/bt2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="自定义显示位置" />
<Button
android:id="@+id/bt3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="带图片" />
<Button
android:id="@+id/bt4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="在其他线程中" />
</LinearLayout>
Activity:
public class MainActivity extends Activity implements OnClickListener {
Button bt1, bt2, bt3, bt4, bt5;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt1 = (Button) findViewById(R.id.bt1);
bt2 = (Button) findViewById(R.id.bt2);
bt3 = (Button) findViewById(R.id.bt3);
bt4 = (Button) findViewById(R.id.bt4);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
bt3.setOnClickListener(this);
bt4.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Toast toast;
switch (v.getId()) {
case R.id.bt1:
// 默认显示
Toast.makeText(MainActivity.this, "默认显示", 1).show();
break;
case R.id.bt2:
// 自定义显示位置
toast = Toast.makeText(MainActivity.this, "自定义显示位置", 1);
toast.setGravity(Gravity.TOP, 0, 0);
toast.show();
break;
case R.id.bt3:
// 带图片显示
toast = Toast.makeText(MainActivity.this, "带图片显示", 1);
toast.setGravity(Gravity.CENTER, 0, 0);
LinearLayout toastView = (LinearLayout) toast.getView();
ImageView imageView = new ImageView(getApplicationContext());
imageView.setImageResource(R.drawable.pig);
toastView.addView(imageView);
toast.show();
break;
case R.id.bt4:
// 在其他线程中显示
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(MainActivity.this, "在线程中使用Toast", 1).show();
Looper.loop();
}
}).start();
break;
default:
break;
}
}
}