在 Android 视图中设置的背景颜色抛出错误

Background colour set in Android view throwing error

提问人:SaAsh Techs 提问时间:6/26/2023 更新时间:6/27/2023 访问量:44

问:

我想在我的 Android 应用程序中显示 Toast,而无需向现有函数“ShowToast”添加额外的参数/参数/输入,因为 ShowToast 已经在许多 java 文件中使用。所以我不能到处添加额外的输入参数。

这是我的代码,我通过HTML字体标签添加文本颜色,效果很好。

public static void ShowToast(Context context, String Message){
    Toast toast = Toast.makeText(context, Html.fromHtml("<font color='#FF0001' ><b>" + Message + "</b></font>"), Toast.LENGTH_LONG);
    toast.getView().setBackgroundColor(Integer.parseInt("#000000"));
    toast.setGravity(Gravity.TOP, 0, 0);
    toast.show();
}

但是当我添加setBackgroundColor时,应用程序挂起并出现以下错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setBackgroundColor(int)' on a null object reference
  

任何人都可以帮忙说明同一条线上的替代方案是什么?

提前致谢。

android nullpointerexception 背景颜色 android-toast

评论


答:

0赞 hmzcnbz 6/27/2023 #1

toast.view 方法在 Android 11 之后返回 null。您应该创建一个新custom_toast_background.xml并将其绑定到 Toast

首先,创建一个custom_toast_background.xml布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/container"
          android:orientation="horizontal"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:padding="8dp"
          android:background="#DAAA"
          >
<ImageView android:src="@drawable/image"
           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"
          />

设置 Toast 的布局

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


toast.setView(layout);

评论

0赞 SaAsh Techs 6/27/2023
LayoutInflater li = getLayoutInflater();视图布局 = li.inflate(R.layout.custom_toast_background, (ViewGroup) findViewById(R.id.container));- getLayoutInflater 和 findViewById 无法解决并抛出错误
0赞 hmzcnbz 6/27/2023
尝试view.findViewById(),它应该可以工作。
0赞 SaAsh Techs 6/27/2023
即使这样也行不通