java - 如何根据屏幕尺寸调整按钮大小

标签 java android xml android-layout xml-layout

我是 android 新手,我正在制作一个包含 2 行按钮的布局,其中每行有 3 个按钮。我希望我的应用程序的 UI 能够与任何屏幕尺寸兼容。所以我得到了屏幕宽度和高度(以像素为单位)。因为我以前没有在 android 中工作过,所以我不知道应该使用 px 或 dp 调整按钮,以便它在任何设备上工作? 谢谢。

最佳答案

您不应该使用像素。您应该将 LinearLayoutlayout_weight 一起使用。

下面是一个示例,其中 2 行有 6 个大小相等的按钮。这里的关键点是有 android:layout_width="0dp"android:layout_weight="1"

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Button 1" />
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Button 2" />
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Button 3" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Button 4" />
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Button 5" />
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Button 6" />
    </LinearLayout>
</LinearLayout>

关于java - 如何根据屏幕尺寸调整按钮大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23631736/

相关文章:

android - Google Maps Android API 性能极差

java - 如何使 ImageButton 随机放置在线性布局中? (安卓)

c# - 将 XML 文件读入 TreeView

java - 子类的解码结果不正确

java - 如何使用 Java 将自定义数据写入 TCP 数据包头选项字段?

java - 当条件为假时再次启动for循环java

android - 更改为新的 materin 主题后缺少后退按钮

android - RTMP android 后处理

java - 在 gwt 中设置映射的所有内容时遇到一些严重问题(用 java 编程)

java - 在 Java 中以编程方式将 Word doc 转换为 HTML