java - 如何获取 API>=19 的屏幕中间
问题描述
单击时,该按钮应移动到屏幕中间。但是每次我在不同的设备上得到不同的按钮位置。而且我不知道该如何解决。我使用的这段代码:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
float middleScreen = metrics.xdpi;
final TranslateAnimation animation = new TranslateAnimation(0, -middleScreen, 0, 0);
animation.setDuration(3000);
animation.setFillAfter(true);
buttonToNextView.setAnimation(animation);
解决方案
首先,DisplayMetrics.xdpi
给我们的exact physical pixels per inch of the screen in the X dimension
是不是 x 轴上的像素数。
所以,我们应该使用一半的widthPixels
and heightPixels
(基于屏幕方向)来实现x轴上的屏幕中间。
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
boolean isDisplayPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
float middleScreen = isDisplayPortrait ? metrics.widthPixels / 2 : metrics.heightPixels / 2;
final TranslateAnimation animation = new TranslateAnimation(0, -middleScreen, 0, 0);
animation.setDuration(3000);
animation.setFillAfter(true);
buttonToNextView.setAnimation(animation);
请注意,要将按钮准确地放置在屏幕中间,您需要从middleScreen
值中减去其宽度的一半。
推荐阅读
- python - os 模块 python 正在工作,但输出不正确
- regex - 如何为文本字段实现正则表达式以在 Extjs 中一次允许一个逗号一个点
- laravel - Laravel - 试图获取非对象的属性“名称”
- java - Spring SAML:后退浏览器按钮导致验证 SAML 消息时出错
- ios - React Native 0.60.4 从 0.59.9 升级
- python - 在 TfidfVectorizer 中删除法语和英语中的停用词
- c# - ASP.NET Core Identity,如何覆盖 IdentityRole Name 唯一索引?我想存储关于租户的重复名称
- web-scraping - 基于页面内容的操作
- javascript - 为什么我的选择器无法读取“状态”?状态未定义
- c# - 将列表项从任务添加到组合框