android – 多屏幕分辨率
作者:互联网
参见英文答案 > How do you make layouts for several Android screen sizes? 3个
我正在开发320 * 480的应用程序.如何让应用程序在480 * 854屏幕上运行?当我试图在480 * 854屏幕上运行时,应用程序的原始设计看起来很小.我想为android中的每个屏幕创建单独的布局吗?如果是这样,请提供样品提示以继续.
解决方法:
我已经实现了自己的处理多屏幕分辨率的方法.
您可以通过在运行时以百分比设置LayoutParams来避免此问题
仅在视图/布局具有一些恒定宽度或高度时才会出现问题,例如280dp.如果我们以百分比的形式设置我们的视图/布局的布局参数并且在必要时仅使用常量宽度或高度,其他地方尝试使用match_parent填充空白空间或使用权重并相对于其他视图定义每个视图,解决方案非常简单这将有助于您的布局在几乎所有屏幕分辨率下都很好看
这是一个示例xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/mLayout"
android:layout_width="280px"
android:layout_height="300px" />
</RelativeLayout>
注意:我已经将px用于固定大小的布局的宽度/高度,因为在LayoutParams中layoutParams = new LayoutParams(int width,int height);宽度和高度取值为像素
以下是以百分比表示设置宽度和高度的示例代码
final ViewTreeObserver mLayoutObserver = mLayout.getViewTreeObserver();
mLayoutObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
DisplayMetrics metrics = getResources().getDisplayMetrics();
int deviceWidth = metrics.widthPixels;
int deviceHeight = metrics.heightPixels;
float widthInPercentage = ( (float) 280 / 320 ) * 100;
float heightInPercentage = ( (float) 300 / 480 ) * 100;
int mLayoutWidth = (int) ( (widthInPercentage * deviceWidth) / 100 );
int mLayoutHeight = (int) ( (heightInPercentage * deviceHeight) / 100 );
LayoutParams layoutParams = new LayoutParams(mLayoutWidth, mLayoutHeight);
mLayout.setLayoutParams(layoutParams);
}
});
现在可能有些人想知道这里发生了什么
float widthInPercentage =((float)280/320)* 100
让我解释280是我的LinearLayout的宽度,320是我的设备屏幕的宽度(我正在开发),我知道目前我正在测试分辨率为320 x 480的设备,我正在做的是计算我的布局覆盖的面积百分比然后
int mLayoutWidth =(int)((widthInPercentage * deviceWidth)/ 100)
这里我根据屏幕分辨率计算布局的新宽度,这样你的视图/布局在每个屏幕分辨率上都会看起来完全一样.
结论:如果需要为Views / Layouts设置一些恒定的宽度/高度,请始终在布局文件(即xml)中的px中设置值,然后以编程方式设置LayoutParams.
谷歌Android工程师的建议,我猜你们应该认真考虑将dp / dip单位改为百分比
标签:android,screen-resolution 来源: https://codeday.me/bug/20190716/1482365.html