I want to change background of my custom toast message but I don't want to create a new xml file for each color. More specifically;
This is my custom_toast_border.xml file which is under the drawable directory.
<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"/>
And my custom_toast.xml layout like that
<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 code:
..... 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();
I want to three different color for toast background. Do I have to create separate file for each color? (like custom_toast_border_red, ..._green, .._yellow). Can't I change the background color from within java code? Please be careful, I don't want to change text color, I want to change background color. Most of the answers to previous questions explained how to change the text color.
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