Toast显示在Activity中央
时间: 2024-03-03 16:51:18 浏览: 26
要在Activity中央显示Toast,可以先通过getWindowManager()方法获取当前Activity的WindowManager对象,然后通过getDefaultDisplay()方法获取当前屏幕的大小,最后根据屏幕大小计算出Toast显示的位置。
具体代码如下:
```
Toast toast = Toast.makeText(getApplicationContext(), "Toast显示在屏幕中央", Toast.LENGTH_SHORT);
int xOffset = 0;
int yOffset = 0;
View toastView = toast.getView();
int toastWidth = toastView.getWidth();
int toastHeight = toastView.getHeight();
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int screenWidth = dm.widthPixels;
int screenHeight = dm.heightPixels;
xOffset = (screenWidth - toastWidth) / 2;
yOffset = (screenHeight - toastHeight) / 2;
toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, xOffset, yOffset);
toast.show();
```
这样就可以在Activity中央显示Toast了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)