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>


















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap