在Toast里面显示图标的两种写法
时间: 2023-12-06 14:42:23 浏览: 32
在 Android 中,可以使用以下两种方式在 Toast 中显示图标:
1. 使用 setCompoundDrawablesWithIntrinsicBounds() 方法设置 Toast 中的图标:
```java
Toast toast = Toast.makeText(context, message, duration);
Drawable icon = ContextCompat.getDrawable(context, R.drawable.icon);
toast.getView().setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
toast.show();
```
2. 使用自定义 Toast 布局文件,在布局文件中添加 ImageView 控件来显示图标:
custom_toast.xml:
```xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_toast_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="@color/colorPrimary"
android:padding="16dp">
<ImageView
android:id="@+id/toast_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon"/>
<TextView
android:id="@+id/toast_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/white"/>
</LinearLayout>
```
使用 LayoutInflater.inflate() 方法加载自定义布局文件,并使用 setView() 方法设置 Toast 的视图:
```java
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.custom_toast_layout));
TextView text = layout.findViewById(R.id.toast_text);
text.setText(message);
ImageView icon = layout.findViewById(R.id.toast_icon);
icon.setImageResource(R.drawable.icon);
Toast toast = new Toast(getApplicationContext());
toast.setDuration(duration);
toast.setView(layout);
toast.show();
```