英文:
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 轴上的像素数。
因此,我们应该使用 widthPixels
和 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
值中减去其宽度的一半。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论