Background colour set in Android view throwing error

49 Views Asked by At

I want to show the Toast in my Android app without adding additional parameter/arguments/input to the existing function "ShowToast" since ShowToast is already used in many java files already. So I can't add an additional input argument everywhere.

This is my code where I am adding text colour through HTML font tag which is working fine.

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();
}

But when I add setBackgroundColor, the app hangs with this error:

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

Can anyone please help as to what might be the alternative on the same line?

Thanks in advance.

1

There are 1 best solutions below

3
hmzcnbz On

toast.view method returns null, after Android 11. You should create a new custom_toast_background.xml and bind it to toast

Firstly, create a custom_toast_background.xml layout file

<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"
          />

Set layout of the toast

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


toast.setView(layout);