首页 > 系统 > Android > 正文

Android开发实现自定义Toast、LayoutInflater使用其他布局示例

2020-07-28 13:58:55
字体:
来源:转载
供稿:网友

本文实例讲述了Android开发实现自定义Toast、LayoutInflater使用其他布局。分享给大家供大家参考,具体如下:

内容:

1.自定义样式toast

2.再活动中添加其他布局

实现效果:

步骤:

一、自定义View 引用zidingyixml文件 生成一个布局对象

二、采用Toast 的addView() 方法将该对象添加到Toast对象中

三、显示:Toast.show()

具体实现方法:

public class MainActivity extends Activity {  Toast toast;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    //应用布局文件    View insideView = LayoutInflater.from(MainActivity.this).inflate(R.layout.cell, null);    LinearLayout linearLayout = (LinearLayout) insideView.findViewById(R.id.cell);    ImageView imageView = (ImageView) insideView.findViewById(R.id.image1_Toast);    TextView textView = (TextView) insideView.findViewById(R.id.textToast);    imageView.setImageResource(R.drawable.warming);    textView.setText("你的app 炸了!!");    //建立提示消息对象    toast = new Toast(this);    toast.setView(insideView);  }  //按钮点击时弹出  public void prev(View source){    toast.show();  }}

注:R.layout.cell 中的cell 就是自定义的布局文件

建立步骤 在/values文件夹下 呢哇一个xml文件即可,内容如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout  android:  xmlns:andro  android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:orientation="horizontal">  <ImageView    android:    android:layout_width="wrap_content"    android:layout_height="wrap_content"/>  <TextView    android:    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:textSize="15dp"/></LinearLayout>

最后给出整体的布局文件

<?xml version="1.0" encoding="utf-8" ?><RelativeLayout xmlns:andro  android:layout_width="match_parent"  android:layout_height="match_parent"  android:gravity="center_horizontal">    <Button      android:onClick="prev"      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:layout_alignParentBottom="true"      android:layout_alignParentLeft="true"/></RelativeLayout>

注:采用了 android:onClick="prev" 方法 在布局文件中直接添加了点击事件,故MainActivity中不用手动添加onClickListener

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android控件用法总结》、《Android开发入门与进阶教程》、《Android视图View技巧总结》、《Android编程之activity操作技巧总结》、《Android数据库操作技巧总结》及《Android资源操作技巧汇总》

希望本文所述对大家Android程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表