Toast是一种非常放便的消息提示框,它会在程序界面上显示一个简单的提示信息,可以像用户简单的提示信息。下面的代码是用两个按钮,一个按钮单击显示纯文本的提示,另一个单击显示带图像的提示。
主代码:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//把按钮声明出来
Button btn1=(Button) findViewById(R.id.btn1);
Button btn2=(Button) findViewById(R.id.btn2);
//为按钮添加单击事件
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 添加Toast响应
//其中第三项为显示时间
Toast toast=Toast.makeText(MainActivity.this, "简单的Toast提示", Toast.LENGTH_SHORT);
//显示Toast
toast.show();
}
});
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast toast=new Toast(MainActivity.this);
//设置Toast的显示位置
toast.setGravity(Gravity.CENTER, 0, 0);
//创建一个ImageView
ImageView image=new ImageView(MainActivity.this);
image.setImageResource(R.drawable.ic_launcher);
//添加一个linearLayout
LinearLayout ll=new LinearLayout(MainActivity.this);
//向LinearLayout添加图片和View
ll.addView(image);
//创建TextView
TextView textView=new TextView(MainActivity.this);
textView.setText("带图像的提示");
textView.setTextColor(Color.BLUE);
textView.setTextSize(40);
ll.addView(textView);
//设置Toast显示自定义的View
toast.setView(ll);
//设置Toast的显示时间
toast.setDuration(Toast.LENGTH_SHORT);
toast.show();
}
});
}
}
XML布局代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btn1"
android:id="@+id/btn1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btn2"
android:id="@+id/btn2"
/>
</LinearLayout>
运行效果: