Android---59---Toast的使用,android中toast的用法
原本以為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;@Overrideprotected 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);}@Overridepublic 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() {@Overridepublic void run() {Looper.prepare();Toast.makeText(MainActivity.this, "線上程中使用Toast", 1).show();Looper.loop();}}).start();break;default:break;}}}