E/Toast: setGravity() shouldn't be called on text toasts, the values won't be used
时间: 2024-03-03 21:51:20 浏览: 59
如果出现了 "E/Toast: setGravity() shouldn't be called on text toasts, the values won't be used" 的错误提示,是因为在使用Toast时调用了setGravity()方法,而这个方法只适用于自定义Toast的布局。
要解决这个问题,可以使用Toast的setView()方法来设置自定义的布局,然后通过布局中的控件来显示文本内容和设置布局的位置。
具体代码如下:
```
// Inflate the Layout
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.custom_toast_layout));
// Set the text
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Toast显示在屏幕中央");
// Show the Toast
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
int xOffset = 0;
int yOffset = 0;
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int screenWidth = dm.widthPixels;
int screenHeight = dm.heightPixels;
xOffset = (screenWidth - layout.getWidth()) / 2;
yOffset = (screenHeight - layout.getHeight()) / 2;
toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, xOffset, yOffset);
toast.show();
```
这样就可以在中央显示自定义布局的Toast了。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)