Toast可以提供非常简单的提示信息。
特点:
- 不能获得焦点
- 显示一段时间后自动消失
Toast类似于对话框,但功能仅限于文本提示或自定义的简单View。
public class MainActivity extends Activity {
private Button button1,button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button)findViewById(R.id.button1);
button2 = (Button)findViewById(R.id.button2);
button1.setOnClickListener(new Listener());
button2.setOnClickListener(new Listener());
}
class Listener implements OnClickListener{
@Override
public void onClick(View v) {
if(v==button1){
Toast toast = Toast.makeText(MainActivity.this, "Toast提示消息",Toast.LENGTH_LONG);
toast.show();
}
if(v==button2){
//自定义View
Toast toast = new Toast(MainActivity.this);
ImageView image = new ImageView(MainActivity.this);
image.setImageResource(R.drawable.ic_launcher);
TextView text = new TextView(MainActivity.this);
text.setText("Toast小提示");
text.setTextSize(30);
LinearLayout ll = new LinearLayout(MainActivity.this);
ll.setOrientation(0);
ll.addView(image);
ll.addView(text);
//toast显示自定义View
toast.setView(ll);
//toast显示时间
toast.setDuration(Toast.LENGTH_SHORT);
toast.show();
}
}
}
[2014-04]