I want to create a toast message with background color is white and message color is black. My toast message is:
Toast.makeText(Logpage.this, \"Please Give
use this way
Toast toast = Toast.makeText(MainActivity.this, R.string.toastMessage, Toast.LENGTH_LONG);
toast.getView().setBackgroundColor(Color.parseColor("#F6AE2D"));
toast.show();
Change Toast Colours without any additional Layouts, 2018
This is a very easy way I've found of changing the colour of the actual image background of the Toast as well as the text colour, it doesn't require any additional layouts or any XML changes:
Toast toast = Toast.makeText(context, message, duration);
View view = toast.getView();
//Gets the actual oval background of the Toast then sets the colour filter
view.getBackground().setColorFilter(YOUR_BACKGROUND_COLOUR, PorterDuff.Mode.SRC_IN);
//Gets the TextView from the Toast so it can be editted
TextView text = view.findViewById(android.R.id.message);
text.setTextColor(YOUR_TEXT_COLOUR);
toast.show();
Adding to @AndroidKiller's answer, you can also set the gravity
and a custom TextView
among other things like so:
Toast toast = Toast.makeText(context, context.getResources().getString(resID), Toast.LENGTH_LONG);
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
View toastView = li.inflate(R.layout.toast_hint_layout, null);
TextView text = (TextView) toastView.findViewById(R.id.hint_text_tv);
text.setText(resID);
toast.setView(toastView);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toastView.setBackgroundResource(R.drawable.toast_9_patch);
toast.show();
Note, your background drawable should be a nine-patch PNG
You can even put an ImageView
, and multiple TextView
s in with XML like this:
<LinearLayout android:id="@+id/layout_root"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="32dp"
android:layout_height="43dp"
android:src="@drawable/lightbulb"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:orientation="vertical"
>
<TextView
android:id="@+id/hint_text_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ccc"
android:textSize="14dp"
/>
<TextView
android:id="@+id/hint_text_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="(disable hints in preferences)"
android:textColor="#555"
android:textSize="11dp"
/>
</LinearLayout>
</LinearLayout>