toast组件小结

  1. 简介:toast是“吐司”的意思,它属于android杂项组件,是一个简单的消息提示框,类似于javascript中的alert. 
  2. 作用
  • 显示文本
  • 显示图片
  • 显示图文

    3.常用方法

       show():显示消息提示框

       makeText(Context context,Charsquence text,int duration):创建一个toast对象

       setView(View view):该Toast显示的view组件

    4.代码演示

       

MainActivity.class
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void findOne(View v){
        Toast.makeText(this,"显示文本",Toast.LENGTH_LONG).show();
    }
    public void findTwo(View v){
        Toast toast = new Toast(this);
        ImageView imageView = new ImageView(this);
        imageView.setImageResource(R.drawable.ic_launcher);
        toast.setView(imageView);
        toast.setGravity(Gravity.TOP,0,0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.show();
    }
    public void findThree(View v){
        Toast toast = new Toast(this);

        TextView tv = new TextView(this);
        tv.setText("安卓开机图片");

        ImageView imageView = new ImageView(this);
        imageView.setImageResource(R.drawable.ic_launcher);

        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.addView(imageView);
        layout.addView(tv);
        toast.setView(layout);

        toast.setGravity(Gravity.CENTER,0,0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.show();
    }

}

  

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.langdon.taiyang.androidtest.MainActivity">
    <Button
        android:text="toast显示文本"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/toidOne"
        android:onClick="findOne"
        android:layout_gravity="center_horizontal"
         />
    <Button
        android:text="toast显示图片"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/toidTwo"
        android:onClick="findTwo"
        android:layout_gravity="center_horizontal"/>
    <Button
        android:text="toast显示图文"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/toidThree"
        android:onClick="findThree"
        android:layout_gravity="center_horizontal"/>
</LinearLayout>

  

    5.注意点

posted on 2016-11-23 22:13  泰洋  阅读(1274)  评论(0编辑  收藏  举报

导航