Toast用法


應用場景:彈出提示信息

主界面:

代碼如下:

復制代碼
 @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        init();
    }
    private void init()
    {
        defaultToastBtn = (Button) findViewById(R.id.defaultToastBtn);
        customLocationBtn = (Button) findViewById(R.id.customLocationBtn);
        imageToastBtn = (Button) findViewById(R.id.imageToastBtn);
        customToastBtn = (Button) findViewById(R.id.customToastBtn);
        otherThreadBtn = (Button) findViewById(R.id.otherThreadBtn);
        
        defaultToastBtn.setOnClickListener(this);// 設置監聽
        customLocationBtn.setOnClickListener(this);
        imageToastBtn.setOnClickListener(this);
        customToastBtn.setOnClickListener(this);
        otherThreadBtn.setOnClickListener(this);
    }
復制代碼

1.默認樣式的Toast

代碼如下:

Toast.makeText(getApplicationContext(), "默認樣式的Toast", Toast.LENGTH_SHORT).show();// 顯示時間較短

2.自定義位置的Toast

代碼如下:

Toast toast = Toast.makeText(getApplicationContext(), "自定義位置 的Toast", Toast.LENGTH_LONG);//顯示時間較長 
toast.setGravity(Gravity.CENTER, 0, 0);// 居中顯示
toast.show();

3.帶圖片的Toast

代碼如下:

復制代碼
Toast toast = Toast.makeText(getApplicationContext(), "帶圖片的Toast", 3000);// 顯示時間也可以是數字
toast.setGravity(Gravity.TOP, 0, 0);// 最上方顯示
LinearLayout toastLayout = (LinearLayout) toast.getView();
ImageView imageView = new ImageView(getApplicationContext());
imageView.setImageResource(R.drawable.icon);
toastLayout.addView(imageView, 0);// 0 圖片在文字的上方 , 1 圖片在文字的下方
toast.show();
復制代碼

4.完全自定義的Toast

代碼如下:

復制代碼
LayoutInflater inflater = getLayoutInflater();// LayoutInflater對象
View layout = inflater.inflate(R.layout.custom_view, null);
ImageView imageView = (ImageView) layout.findViewById(R.id.imageView);
TextView text = (TextView) layout.findViewById(R.id.textView);
imageView.setImageResource(R.drawable.icon);
text.setText("完全自定義的Toast");
Toast toast = new Toast(getApplicationContext());
// 底部 、水平居中,X偏移50 Y偏移50
toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 50, 50);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
復制代碼

5.來自其他線程的Toast

代碼如下:

復制代碼
handler = new Handler();
new Thread(new Runnable()
{
    public void run()
        {
            show();
        }
}).start();
復制代碼
復制代碼
private void show()
{
    handler.post(new Runnable()
    {
        @Override
        public void run()
{ Toast.makeText(getApplicationContext(), "Hello,I come from other thread!", 5000).show(); } }); }
復制代碼

注:getApplicationContext()  表示它的生命周期是整個應用,應用摧毀它才被摧毀。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM