使用Toast来生成提示消息,如下步骤:
1、调用Toast的构造器或makeText()静态方法创建一个Toast对象;
2、调用Toast的方法设置消息提示的对齐方式,页边距等;
3、调用Toast的show()方法将它显 出来。
具体代码如下:
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:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context="com.example.home.toast.MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/simple" android:text="普通提示"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/bn" android:text="带图片的提示" android:layout_marginTop="50dp"/> </LinearLayout>
Activity java代码:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button simple=(Button)findViewById(R.id.simple); //为按钮的单击事件绑定事件监听器 simple.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //创建一个Toast提示信息,最后参数是设置Toast信息的持续时间 Toast toast=Toast.makeText(MainActivity.this,"简单的提示信息",Toast.LENGTH_SHORT); toast.show(); } }); Button bn=(Button)findViewById(R.id.bn); //为单击按钮事件绑定事件监听器 bn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //创建一个Toast提示信息 Toast toast=new Toast(MainActivity.this); //设置Toast的显示位置 toast.setGravity(Gravity.CENTER,0,0); //创建一个ImageView ImageView imageView=new ImageView(MainActivity.this); imageView.setImageResource(R.drawable.tools); //创建一个Linnerlayout容器 LinearLayout ll=new LinearLayout(MainActivity.this); //向LinerLayout中添加图片,原有的View ll.addView(imageView); //创建一个TextView TextView textView=new TextView(MainActivity.this); textView.setText("带图片的提示信息"); //设置文本框内字号的大小和字体颜色 textView.setTextSize(24); textView.setTextColor(Color.MAGENTA); ll.addView(textView); //设置Toast显示自定义View toast.setView(ll); //设置Toast的显示时间 toast.setDuration(Toast.LENGTH_LONG); toast.show(); } }); } }