首页 > 解决方案 > 如何在没有多个背景 xml 的情况下更改自定义 toasts 消息的背景?

问题描述

我想更改自定义 toast 消息的背景,但我不想为每种颜色创建一个新的 xml 文件。进一步来说;

这是我在可绘制目录下的custom_toast_border.xml文件。

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content"
android:layout_width="match_parent">
<stroke android:width="1dp" android:color="@color/toastGreen" />
<corners android:radius="0dp" />
<gradient android:startColor="@color/toastGreen"
    android:endColor="@color/toastGreen"
    android:angle="-90"/>

我的custom_toast.xml布局就是这样

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_toast_container"
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="@drawable/custom_toast_border"
android:layout_gravity="bottom|center_horizontal"
android:orientation="horizontal">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="80dp">

    <TextView
        android:id="@+id/tv_toast_message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:fontFamily="@font/futura_book"
        android:padding="3dp"
        android:text="Toast Message"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="17sp" />

</LinearLayout>

Java代码:

    ..... inflater = getLayoutInflater();
    layout = inflater.inflate(R.layout.custom_toast,null);
    toast_message = layout.findViewById(R.id.tv_toast_message);
    Toast toast = new Toast(getActivity().getApplicationContext());
        //View view = toast.getView(); //It is failed. Null object referance
        //view.getBackground().setColorFilter(getResources().getColor(R.color.toastRed), PorterDuff.Mode.SRC_IN);
        toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.show();

我想为吐司背景设置三种不同的颜色。我必须为每种颜色创建单独的文件吗?(如 custom_toast_border_red、..._green、.._yellow)。我不能从 java 代码中更改背景颜色吗? 请注意,我不想改变文字颜色,我想改变背景颜色。以前问题的大多数答案都解释了如何更改文本颜色。

标签: androidcustom-controlsbackground-colortoastcustom-view

解决方案


GradientDrawable containerDrawable = (GradientDrawable) layout.findViewById(R.id.custom_toast_container).getBackground();
containerDrawable.setColor(Color.GREEN); // CHANGE BG COLOR
containerDrawable.setStroke(1,Color.GREEN); // CHANGE THE STROKE COLOR

推荐阅读