多种屏幕分辨率[重复]

2023-12-07

我正在开发 320*480 的应用程序。如何让应用程序在480*854屏幕上运行?当我尝试在 480*854 屏幕下运行时,应用程序原始设计看起来很小。我想为 android 中的每个屏幕创建单独的布局吗?如果是这样,请向我提供示例提示以继续。


我已经实现了我自己的方式处理多种屏幕分辨率.

您当然可以通过设置来避免这个问题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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

多种屏幕分辨率[重复] 的相关文章

随机推荐