服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Android - Android开发实现自定义Toast、LayoutInflater使用其他布局示例

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

2022-10-07 16:32水中鱼之1999 Android

这篇文章主要介绍了Android开发实现自定义Toast、LayoutInflater使用其他布局,涉及Android自定义Toast与界面布局相关操作技巧,需要的朋友可以参考下

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

内容:

1.自定义样式toast

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

实现效果:

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

步骤:

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

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

三、显示:Toast.show()

具体实现方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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文件即可,内容如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?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>

最后给出整体的布局文件

?
1
2
3
4
5
6
7
8
9
10
11
12
<?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程序设计有所帮助。

原文链接:https://blog.csdn.net/qq_43377749/article/details/84987652

延伸 · 阅读

精彩推荐