【问题标题】:Android : Varying the button's size as per screen sizesAndroid:根据屏幕尺寸改变按钮的大小
【发布时间】:2025-12-07 09:35:01
【问题描述】:

我想让我在 android xml 中的所有视图都根据屏幕大小进行放大。反正我能做到。我不能完全使用 match_parent 或 wrap_content。

这是一个相对布局的按钮。我想根据屏幕大小改变它的大小

   <Button
        android:id="@+id/simple_b_1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/simple_b_4"
        android:layout_alignLeft="@+id/simple_check"
        android:text="1"
        android:width="66dp" />

【问题讨论】:

    标签: android xml views screen-size


    【解决方案1】:

    编辑

    好的,您可以在 values 文件夹中定义不同的维度文件,并命名 values 文件夹,例如 values(第一个默认文件夹) values-sw480dp、values-sw600dp 和 values-sw700 用于屏幕尺寸高达 3.2 英寸的值 values-sw480dp 用于 3.3 英寸到 5.7 英寸的屏幕尺寸 values-sw600dp 用于 7 英寸的屏幕尺寸 values-sw720dp 用于屏幕尺寸 10 英寸 android 会在你这样定义时自动调整所有屏幕

    以下是您可以在 vaules-sw480dp 文件夹中为屏幕尺寸 3.3 到 5.7 英寸定义的尺寸文件示例,您也可以在不同的值文件夹中定义其余屏幕尺寸

    <?xml version="1.0" encoding="utf-8"?>
     <resources>
    
       <dimen name="layout_marginBottom">38dp</dimen>
       <dimen name="layout_marginLeft">70dp</dimen>
       <dimen name="layout_marginRight">70dp</dimen>
    
    </resources>
    

    现在您可以在如下布局中使用它

    <Button
                    android:id="@+id/mybutton"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentRight="true"
    
                    android:layout_marginBottom="@dimen/layout_marginBottom"<----- these   
                    //are the dimens file reference it like that in Layout folder android 
                    //will pick automatically
    
                    android:layout_marginRight="@dimen/layout_marginRight"
    
                    android:background="@drawable/frame" />
    

    【讨论】:

    • 我的意思是,如果我在 nexus 5 和 nexus 7 上使用相同的布局,按钮大小应该会相应变化。现在尺寸是固定的,所以如果我在nexus 5中使用它是正确的,但如果我在nexus 7中使用它,那么按钮的格式不正确。
    • 我正在使用多个按钮。上面的代码只是我如何在相对布局中定义这些按钮的一个示例。
    • 这不会缩放按钮,只会改变它们之间的距离......我希望按钮根据比例调整大小......但我想我可以使用这个维度进行设置增加按钮的宽度和高度,它可能会起作用......
    最近更新 更多