Android Toast position top


To display an Android Toast message at the Top of an Activity screen (over the ActionBar) we have to make use of setGravity() function. To do so we have to create a Toast Object, lets see an example

ToastActivity.java
package com.code2care.toast;
		
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;


public class ToastActivity extends ActionBarActivity {

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



     

    public void displayToast(View view) {
    	
    	
    	Toast toast = Toast.makeText(getApplicationContext(),
    	        "This toast message will be displayed at the top of the activity screen!",
    	        Toast.LENGTH_SHORT);
    	
    	
    	toast.setGravity(Gravity.TOP, 0, 0);
    	toast.show();
    	
    	
    	
    }
}
activity_toast.xml
<LinerLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.code2care.toast.MainActivity" >

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:onClick="displayToast"
        android:text="Display Toast at Top" />

</LinerLayout>





Recent Posts:
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, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.