欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

自定义Toast 显示文字和图片

程序员文章站 2022-06-05 18:48:17
...
Toast用于提示当前应用的状态信息,如网络连接状态等,一般是显示一段文字,也可以定制自己的Toast。下面举例说明:
 
public class MyActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);

//点击显示图片
button1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Toast toast = new Toast(MyActivity.this);
ImageView view = new ImageView(MyActivity.this);
view.setImageResource(R.drawable.icon);
toast.setView(view);
toast.setDuration(Toast.LENGTH_LONG);
toast.show();
}
});

//点击显示文字和图片
button2.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Toast toast = new Toast(MyActivity.this);
LinearLayout layout = new LinearLayout(MyActivity.this);
layout.setOrientation(LinearLayout.VERTICAL);

ImageView view = new ImageView(MyActivity.this);
view.setImageResource(R.drawable.icon);
TextView textView = new TextView(MyActivity.this);
textView.setText("Toast显示文字和图片");

layout.addView(view);
layout.addView(textView);
toast.setView(layout);
toast.show();

}
});
}
}


运行结果如下
当点击第一个按钮后,显示图片Toast:

[img]http://dl.iteye.com/upload/attachment/350252/ed10744e-7a90-3634-bc1c-86ae0950887c.jpg[/img]

当点击第二个按钮后,显示文字和图片Toast:

[img]http://dl.iteye.com/upload/attachment/350254/2b41f557-9399-374f-9033-3d5d16fc98c2.jpg[/img]
相关标签: 网络应用