【问题标题】:How to set no height for a widget in Android Studio?如何在 Android Studio 中为小部件设置不高度?
【发布时间】:2016-10-12 08:17:17
【问题描述】:

我正在学习 Android 开发,并且正在尝试制作一个简单的计算器。我在计算器的布局上遇到了一些问题。在我看来,发布整个 xml 代码太笨拙了,所以我只发布我认为重要的 sn-ps。

我将垂直 LinearLayout 作为最顶层的父级,然后它有 2 个子级,一个水平 LinearLayout,(由一个显示您的输入的 textView 和一个告诉计算的按钮组成)和一个 GridLayout,这将是0-9 按钮和操作符。

问题是,网格布局将是一个带有按钮的 4x4 网格,当我想设置第一行按钮时,每个按钮都需要获取 layout_height,它不能留空,如果我将其值设置为match_parent,那么仅该按钮就会填满整个屏幕。

那么如何使用 layout_height 解决这个问题,是否有一些解决方法或者为网格制作多个 LinearLayout 会更好?如果您有任何其他问题,请随时提出,以便我解释。

这里是子 LinearLayout 和 GridLayout xml 代码:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:layout_weight="1"
    android:background="@color/colorLight"
    android:orientation="horizontal">

<GridLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="8"
    android:background="@color/colorLight"
    android:>

【问题讨论】:

  • 你能设置 grid_column 吗?它不能解决你的问题?
  • 你能用GridView代替GridLayout吗?
  • 使用 0dp 作为视图的高度。或将视图可见性设置为 GONE。我更喜欢第二种选择。
  • @Amir,我现在试试看它是否有效。 SQLiteNoob,我需要使用网格布局以获得更好的可定制性。 Bob Malooga,当我将高度设置为 0dp 时,按钮会消失,就像 GONE 可见性一样。我需要按钮可见。以应用商店中的任何简单计算器为例。
  • 将 4 个 LinearLayout 做成一个网格并为每个它们添加按钮会是一件好事吗?它会起作用,但它会是一个好的解决方案吗?

标签: android android-layout


【解决方案1】:

对不起,我误解了你的问题。 如果您使用 API 21 或更高版本,可以使用columnCount 获取。

请参考that answerthat answer

【讨论】:

  • 谢谢回答。问题不在于子布局,我为它们设置了 layout_weight 并且它们应该适合。问题是当我向网格布局添加一个按钮时,该按钮需要有一个 layout_height 值,如果我将其设置为 match_parent,它将填满整个屏幕,如果我将其设置为 0dp,它将消失。
【解决方案2】:

针对各种屏幕尺寸进行分类的最佳方法是使用weight 属性。对于GridLayout,没有,根据documentation

查看此答案以获取想法,例如嵌套LinearLayoutsGridLayout (not GridView) how to stretch all children evenly

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多