android toast用法总结(一)

1,Toast简单用法:

//利用工厂方法构造一个简单的Toast,并链式结构的直接进行提示
Toast.makeText(this, "这是一个Toast示",
Toast.LENGTH_LONG).show();

2,Toast也是一个容器,可以包含各种View,承载着它们显示出来,

//初始化Toast
Toast toast = new Toast(this);
//设置显示时间,可以选择Toast.LENGTH_LONG或者Toast.LENGTH_SHORT
toast.setDuration(Toast.LENGTH_LONG); 
//承载一个TextView,用来显示文字
TextView tview = new TextView(this);
//设置TextView的值
tview.setText("这是一个Toast提示");
//设置TextView的布局
tview.setLayoutParams(new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
//Toast承载该view
toast.setView(tview);
//显示Toast
toast.show();

3,包含Layout,并显示:

Toast toast = new Toast(this);
toast.setDuration(Toast.LENGTH_LONG);
TextView tview = new TextView(this);
ImageView iView = new ImageView(MainActivity.this);
tview.setText("Toast提示");
            iView.setImageResource(R.drawable.ic_launcher);
//tview.setLayoutParams(new LayoutParams(
//LinearLayout.LayoutParams.WRAP_CONTENT,
//LinearLayout.LayoutParams.WRAP_CONTENT));
// Toast承载该layout
LinearLayout layout = new LinearLayout(MainActivity.this);
            layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(iView);
layout.addView(tview);
toast.setView(layout);
toast.setGravity(Gravity.CENTER, 0, 0);
// toast.setMargin(0f, 0.5f);
toast.show();

android toast用法总结(一)_第1张图片

Toast.setView源码:

 View mNextView;
/**
     * Set the view to show.
     * @see #getView
     */
    public void setView(View view) {
        mNextView = view;
    }

4,获得toast的布局

Toast toast1=Toast.makeText(this, "显示带图片的toast", 3000); 
toast1.setGravity(Gravity.CENTER, 0, 0);  
ImageView imageView= new ImageView(getApplicationContext()); 
imageView.setImageResource(R.drawable.ic_launcher); 
//获得toast的布局 
LinearLayout toastView = (LinearLayout) toast1.getView(); 
toastView.setOrientation(LinearLayout.VERTICAL); 
//将ImageView在加入到此布局中的第一个位置 
toastView.addView(imageView, 0); 
toast1.setView(toastView);
toast1.show(); 

5,

Toast toast3 = Toast.makeText(this, "这是一个代图片的Toast!", Toast.LENGTH_LONG);
ImageView imageView3 = new ImageView(this);
            imageView3.setImageResource(R.drawable.ic_launcher);
View toastView3 = toast3.getView();
LinearLayout linearLayout3 = new LinearLayout(this);
            linearLayout3.setOrientation(LinearLayout.VERTICAL);
             // 将ImageView和ToastView合并到Layout中 
linearLayout3.addView(imageView3);
linearLayout3.addView(toastView3);
// 替换掉原有的ToastView 
toast3.setView(linearLayout3);
toast3.show();

你可能感兴趣的:(toast,android)