digo
digo

Reputation: 45

Change the color of Toast

How I can change the color of the message Toast?

Here my code:

 public void checkButton(View view) {


    if(count < 0){
        Toast.makeText(getApplicationContext(), "Incorreto!",
                Toast.LENGTH_SHORT).show();
    }

    else if(count == 0){
        Toast.makeText(getApplicationContext(), "Correto",
                Toast.LENGTH_SHORT).show();
        }

    }
}

Upvotes: 3

Views: 12432

Answers (3)

Mithun Adhikari
Mithun Adhikari

Reputation: 569

The method to change the color, position and background color of toast is:

    Toast toast=Toast.makeText(getApplicationContext(),"This is advanced toast",Toast.LENGTH_LONG);
    toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT,0,0);
    View view=toast.getView();
    TextView  view1=(TextView)view.findViewById(android.R.id.message);
    view1.setTextColor(Color.YELLOW);
    view.setBackgroundResource(R.color.colorPrimary);
    toast.show();

For line by line explanation: https://www.youtube.com/watch?v=5bzhGd1HZOc

Upvotes: 5

AgileNinja
AgileNinja

Reputation: 944

Create a custom Toast layout, such as correct_toast.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/toast_layout_root"
          android:orientation="horizontal"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:padding="8dp"
          android:background="#DAAA">
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textColor="#FFF"
              />
</LinearLayout>

Then in the java code, construct the toast with this view:

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

TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("This is a custom toast");

Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

This way, you are able to change the color of the background, and/or change the color of the text.

Upvotes: 3

Bogdan Ustyak
Bogdan Ustyak

Reputation: 5839

Toast toast = Toast.makeText(getApplicationContext(), "Correto!",
                Toast.LENGTH_SHORT);

TextView toastMessage = (TextView) toast.getView().findViewById(android.R.id.message);
toastMessage.setTextColor(Color.RED);
toast.show();

Upvotes: 11

Related Questions