在Toast里面显示图片
时间: 2023-12-03 18:45:47 浏览: 51
要在Toast中显示图片,你需要使用自定义Toast。以下是一个示例代码:
```java
// 建立自定义Toast的布局文件,例如:toast_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="12dp"
android:background="#DAAA"
>
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
/>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:text="This is a custom Toast"
/>
</LinearLayout>
// 在代码中创建自定义Toast
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.custom_toast_layout));
ImageView image = (ImageView) layout.findViewById(R.id.imageView);
image.setImageResource(R.drawable.ic_launcher);
TextView text = (TextView) layout.findViewById(R.id.textView);
text.setText("This is a custom Toast");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
```
在此示例中,我们首先创建了一个自定义的布局文件toast_layout.xml,其中包含一个ImageView和一个TextView。然后,我们使用LayoutInflater从布局文件中创建一个视图。接着,我们设置ImageView的图像资源和TextView的文本内容。最后,我们创建一个Toast对象,将自定义的布局视图设置为Toast的视图,并显示它。
请注意,你需要将图像资源放在drawable文件夹中,并将其引用为R.drawable.ic_launcher。另外,也可以根据需要修改布局文件和代码来满足你的需求。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)