如何在 API>=19 的情况下获取屏幕中央位置。

huangapple go评论85阅读模式
英文:

How to get the middle of the screen for 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);
英文:

The button should move to the middle of the screen when clicked. But every time I get different position of button in different devices. And I don't know how can I fix it.
This code what I use:

 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);

答案1

得分: 2

首先,DisplayMetrics.xdpi 给出的是屏幕在 X 轴上每英寸的精确物理像素数,而不是 x 轴上的像素数。

因此,我们应该使用 widthPixelsheightPixels 的一半(根据屏幕方向)来实现屏幕 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 值中减去其宽度的一半。

英文:

First of all, what DisplayMetrics.xdpi gave us is the exact physical pixels per inch of the screen in the X dimension which is not the number of pixels on the x-axis.

So, we should use half of widthPixels and heightPixels (based on screen orientation) to achieve the middle of the screen on the x-axis.

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);

Notice that to place the button exactly at the middle of the screen, you need to subtract half of its width from the middleScreen value.

huangapple
  • 本文由 发表于 2020年9月22日 23:08:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/64012566.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定