温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-20 17:05:04 来源:脚本之家 阅读:115 作者:水中鱼之1999 栏目:移动开发

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

内容:

1.自定义样式toast

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

实现效果:

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

步骤:

一、自定义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:id="@+id/cell"
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="horizontal">
  <ImageView
    android:id="@+id/image1_Toast"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
  <TextView
    android:id="@+id/textToast"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="15dp"/>
</LinearLayout>

最后给出整体的布局文件

<?xml version="1.0" encoding="utf-8" ?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  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程序设计有所帮助。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI