首页 > 解决方案 > 如何获取 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);

标签: javaandroidandroid-animationandroid-screen

解决方案


首先,DisplayMetrics.xdpi给我们的exact physical pixels per inch of the screen in the X dimension是不是 x 轴上的像素数。

所以,我们应该使用一半的widthPixelsand 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值中减去其宽度的一半。


推荐阅读