安卓多彩提示框(Toast)

3
我想要一个多彩的烤面包片。像这样:

Multi Color Toast

我查看了不同的教程,以更改xml中的布局来创建自定义Toast,但它们都没有解释如何添加不同的颜色,就像上面的照片一样。
我该怎么做?
================================
答案
================================
在您所有的帮助下,我设计了一个简单的方法(Method())来更容易地调用彩色Toast。
res/layout/toast_layout.xml
<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:paddingLeft="12dp"
    android:paddingRight="12dp"
    android:paddingBottom="6dp"
    android:paddingTop="6dp"
    android:background="#DAAA"
    >
    <TextView android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>

src/PROJECTNAME/FILENAME.java

// Color Toast(String1,String2,Color)
// Toastbackground = White
// String1 = Dark Gray
// String2 - **CASE SENSITIVE**
//   = "same" = Dark Gray, or
//   = "purple" = Purple, or
//   = "orange" = Orange

    public void CToast(String t1, String t2, String c) {
        if (c == "same") {
            c = "444444";
        } else if (c == "purple") {
            c = "6600FF";
        } else if (c == "orange") {
            c = "ffcc00";
        }

        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.toast_layout,
                (ViewGroup) findViewById(R.id.toast_layout_root));
        TextView textCToast = (TextView) layout.findViewById(R.id.text);

        String text2 = "<font color=#444444>" + t1 + "</font> <font color=#" + c + ">" + t2 + "</font";
        textCToast.setText(Html.fromHtml(text2));

        Toast toast = new Toast(this);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(layout);
        toast.show();
    }

希望这能帮到你!谢谢大家。
3个回答

7
在您的自定义布局中放置一个textView。
String text = "This is <font color='red'>red</font>. This is <font color='blue'>blue</font>.";
textView.setText(Html.fromHtml(text), TextView.BufferType.SPANNABLE);

N.B.:此示例来自这里


4

尝试做这个,我希望这就是你真正想要的。

richTextView = (TextView)findViewById(R.id.rich_text);  

    // this is the text we'll be operating on  
    SpannableString text = new SpannableString("hello how are you");  

    // make "hello" to (characters 0 to 5) red color 
    text.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, 0);  

richTextView.setText(text, BufferType.SPANNABLE);  

如果你想将它显示为“Toast”,请使用以下代码,而不是setText:
Toast.makeText(context, text, Toast.LENGTH_LONG).show();

enter image description here


这基本上是我建议的,但是加上可复制的代码 :) +1 - Shark

3

我认为你应该使用SpannableText来进行文本格式化 - 这样可以让你在字符串中应用颜色、样式以及插入表情等。

所以,这是我第一个想要尝试并解决问题的想法。

我确信这对于绘制文本和多彩通知是有效的。 或者你只需要应用可扩展的过滤器。请参见这里


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