Change Android Toast background color


You must have seen that by default we get a dark greyish kind of background color for a toast message that is displayed in Android Activity Screen (may vary depending upon what flavor of Android OS you are using). If you want to develop a custom Toast message with a color combination that suits your app design then we can do it programmatically using setBackgroundResource() provided by the Toast Class. Let's see an example, we will change the background color to Yellow and the toast text color to white,

Custom toast color
Custom toast color

We need to create a drawable XML file to achieve this, we will create toast_drawable.xml and store it in the any of the drawable folders under res. We will add a solid tag to set the background color.

File : toast_drawable.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <solid android:color="#ffff00" />

</shape>
File : MainActivity.java
package com.code2care.toast;
	
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
     

    public void displayToast(View view) {
    	
    	
    	Toast toast = Toast.makeText(getApplicationContext(),
    	        "Custom toast background color",
    	        Toast.LENGTH_SHORT);
    	
    	View toastView = toast.getView();
    	toastView.setBackgroundResource(R.drawable.toast_drawable);
    	toast.show();
    	
    }
}
Advertisements
Try Out Code2care Dev Tools:

Advertisements



Android Java Linux Microsoft Google Python macOS Notepad++ Microsoft Teams CSS PHP SharePoint Html Linux C Programs Bootstrap jQuery Sublime Android Studio Facebook Eclipse WhatsApp News MySQL Json HowTos JavaScript FTP S3


Advertisements


Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Tutorials, Trouble-Shooting steps, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.
🎉 We are celebrating the 10th years of Code2care! Thank you for all your support! We hope we made a difference.
We strong support Gender Equality & Diversity.

We stand in solidarity with Ukraine - Make a donation to UNHCR - https://donate.unhcr.org/in/en-in/ukraine-emergency