To display an Android Toast message at the Top of an Activity screen (over the ActionBar) we have to make use of the setGravity() function. To do so we have to create a Toast Object, let's see an example
ToastActivity.javapackage 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>
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!