我已经实现了我自己的方式处理多种屏幕分辨率.
您当然可以通过设置来避免这个问题LayoutParams
在运行时方面百分比
The Problem仅发生于Views/Layouts
有一些常数width or height可以说280dp
. Solution如果我们以编程方式设置布局参数,则非常简单Views/Layouts
按照百分比并且只使用常量width or height必要时,在其他地方尝试使用match_parent
填补空白或使用weights
并定义每一个View
相对于其他Views
这将帮助您的布局在几乎所有屏幕分辨率下看起来都很好
这是一个示例 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>
Notice:我用过px对于固定大小的布局宽度/高度因为在LayoutParams layoutParams = new LayoutParams(int width, int height);
the width
and height
取值为pixels
这是设置的示例代码width and 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
and 320是我的设备屏幕的宽度(我正在开发),我知道目前我正在具有分辨率的设备上进行测试320×480,我正在做的是计算多少钱area我的布局涵盖了百分比进而
int mLayoutWidth = (int) ( (widthInPercentage * deviceWidth) / 100 )
在这里,我根据屏幕分辨率计算布局的新宽度,这样你的Views/Layouts
每一个看起来都一模一样屏幕分辨率.
结论:如果你需要设置一些常量宽度/高度为您Views/Layouts
始终将值设置为px在布局文件(即 xml)中,然后以编程方式设置LayoutParams
.
一个建议谷歌安卓工程师,我想你们应该认真考虑改变dp/dip
单位到percentage