我正在为自己创建一个车载底座应用程序,我有 6 个按钮可以放置应用程序的快捷方式。我设计了横向和纵向模式的布局。我在纵向模式下遇到屏幕尺寸问题。我的图标排列如下:
Text up here
------------
| 1 | 2 |
------------
| 3 | 4 |
------------
| 5 | 6 |
------------
这是按钮的 XML:
<Button
android:id="@+id/btnLaunchSlotOne"
style="@style/launchButton"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_weight="1"
android:layout_marginRight="8dp"
android:padding="10dp"
android:text="Navigation"
android:textColor="#ffffff" />
现在我遇到的问题是,当我在较小的屏幕尺寸上测试应用程序时,按钮似乎没有调整大小,并且它们在底部离开了屏幕。我怎样才能让它们正确缩放?我以为使用“dp”可以解决所有这些问题?
我是否需要以编程方式计算屏幕尺寸?
感谢您的建议/帮助!
最佳答案
使用类似于下面的布局来正确嵌套按钮:
<LinearLayout
android:orientation="vertical">
<TextView>Put your Text here</TextView>
<LinearLayout
android:orientation="horizontal"
android:layout_weightSum="2">
<LinearLayout
android:orientation="vertical"
android:layout_height="fill_parent"
android:layout_width="0dp"
android:layout_weightSum="3"
android:layout_weight="1">
<Button
android:layout_weight="1"/>
<Button
android:layout_weight="1"/>
<Button
android:layout_weight="1"/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_weightSum="3"
android:layout_height="fill_parent"
android:layout_width="0dp"
android:layout_weight="1">
<Button
android:layout_weight="1"/>
<Button
android:layout_weight="1"/>
<Button
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
然后每个按钮需要 0dp 的高度(这允许重量应用并水平缩放按钮)和填充父级的宽度。
诀窍是子元素的权重会导致设置为 0dp 的维度填充到父元素的 weightSum 的百分比。
例如,我有一个线性布局,其中 weightSum 为 3 和 3 个权重为 1 的子按钮。当高度设置为 0dp 时,它们每个将采用父级高度的 1/3 作为它们的高度。当 width 设置为 0dp 时,它们将各自占用父级宽度的 1/3 作为它们自己的宽度。
这是根据百分比宽度或高度组织项目的最佳方式。
顺便说一句,如果您有两个按钮,一个重量为 2,一个重量为 1,那么 1 个按钮将是父级高度/宽度的 33%,另一个按钮是父级高度/宽度的 66%。方便的小技巧,适用于所有屏幕。
关于java - 如何让六个按钮根据屏幕尺寸调整大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10250020/