Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toast.setGravity() does not work in my AVD Nexus 6 API 30

I set the gravity of my toast to make it show on the top of the screen, with code below:

Toast toast = Toast.makeText(getActivity(), "邮箱地址不能为空!", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP, 0, 0);
toast.show();

it does not work in my AVD Nexus 6 API 30 with LogCat message:

E/Toast: setGravity() shouldn't be called on text toasts, the values won't be used

however it seems fine when I install the apk on my phone Nokia X6 with Android 9. please help me!!

like image 277
shopkeeper Avatar asked Nov 25 '20 11:11

shopkeeper


People also ask

Why is toast not working in Android Studio?

You're trying to display a Toast in a background thread. You should do all your UI operations on the main UI thread. The exception RuntimeException: Can't create handler inside thread that has not called Looper. prepare() can be a little cryptic for beginners but essentially it tells you that you're in a wrong thread.

Is Toast deprecated Android?

Custom toast views are deprecated. Apps can create a standard text toast with the makeText(android.

How do I toast a string in Android?

It is the string message that you want the toast to display on the Android Activity screen. String toastTextMsg = "Hello, welcome to Code2care!"; Toast toast = Toast. makeText(MainActivity. this, toastTextMsg , Toast.


1 Answers

As it said in Android documentation about Toast setGravity method, this method doesn't work anymore for devices running API30 or higher. I suppose you have targetSdk set to 30 for your project.

Warning: Starting from Android Build.VERSION_CODES#R, for apps targeting API level Build.VERSION_CODES#R or higher, this method is a no-op when called on text toasts.

SOURCE: https://developer.android.com/reference/android/widget/Toast#setGravity(int,%20int,%20int)

like image 181
BVantur Avatar answered Nov 15 '22 08:11

BVantur