如何在安卓中自定义Toast?

8
在Android中是否可以自定义Toast,例如在其中放置图像图标和按钮?
4个回答

2

你也可以使用常规的makeText()方法,并使用getView()方法设置图片以便在下次查看时显示。

Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
TextView tv = (TextView) toast.getView().findViewById(android.R.id.message);
if (null!=tv) {
    tv.setCompoundDrawablesWithIntrinsicBounds(icon, 0, 0, 0);
    tv.setCompoundDrawablePadding(context.getResources().getDimensionPixelSize(R.dimen.padding_toast));

有趣...不过值得发布 - CoDe
1
是的,就我个人而言,如果您只需要一个图标,那么这是最干净的解决方案。TextView 也可以接受 CharSequence,因此您可以在其中放置一些带有各种内容的 Spannable。 - robUx4

1
XML文件
enter code here`<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/toast_layout_root"
          android:orientation="horizontal"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:padding="8dp"
          android:background="#DAAA"
          >
<ImageView android:src="@drawable/droid"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_marginRight="8dp"
           />
<TextView android:id="@+id/text"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:textColor="#FFF"
          />

'

JAVA 代码

 LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
                               (ViewGroup) findViewById(R.id.toast_layout_root));

TextView text = (TextView) layout.findViewById(R.id.text);
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();

1

你可以使用setView在Toast中放置任何视图,但是我不确定为什么你想把一个按钮放在里面,因为Toast会很快消失。以下内容摘自官方开发者网站:

当视图显示给用户时,它将作为浮动视图出现在应用程序上方,永远不会接收焦点。用户可能正在输入其他内容。我们的想法是尽可能地不引人注目,同时向用户展示您想让他们看到的信息。

因此,Toast只应用于显示信息。对于更复杂的交互,您可以使用Dialog。


嘿,Gregory...从Toast中处理按钮事件是否可能? - CoDe
我从未尝试过,也不会这样做,Toast 只是一个临时显示。如果你真的需要一个按钮,请考虑使用对话框(并最终添加计时器以在给定时间后解除它)。 - Gregory

1

Toast不可聚焦。添加按钮没有意义。但是您可以显示信息。您还可以通过对Toast类进行一些更改来控制其可见性,这意味着您可以隐藏和显示。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接