【问题标题】:Android GridLayout fill_horizontal goes off-screen [duplicate]Android GridLayout fill_horizo​​ntal 离屏[重复]
【发布时间】:2017-01-05 10:24:31
【问题描述】:

我有一个简单的GridLayout

<GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:columnCount="2"
    android:rowCount="1" >

    <TextView
        android:layout_column="0"
        android:layout_row="0"
        android:text="Label"/>

    <EditText
        android:inputType="text"
        android:layout_column="1"
        android:layout_row="0"
        android:text="asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf"
        android:layout_gravity="fill_horizontal"/>
</GridLayout>

但是,这会导致EditText 延伸到屏幕外,如下所示(图片来自 IDE,但在设备上运行时效果相同)。

看起来EditText 实际上是屏幕的整个宽度,而不是GridLayout 单元格的宽度,这就是它离开屏幕的原因。布局中有什么问题导致了这种情况?

【问题讨论】:

标签: android grid-layout android-gridlayout


【解决方案1】:

我不知道你为什么需要 GridView 来解决这个问题,也许你比我更了解,但你可以在这篇文章 Gridview with two columns and auto resized images 中找到对你有用的东西。

在您的情况下,GridView 有 2 列,在每一列中,您都有没有为宽度和高度参数设置任何值的视图,在这种情况下,Android 将它们排除在 wrap_content 之外。

当 TextView 和 EditText 具有 layout_width="wrap_content" 时,它们会将它们自身扩展为一行,直到它们包裹整个内容。这就是为什么你要走出手机屏幕。

试试这个 xml,你会看到预期的行为:

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnCount="2"
android:rowCount="1">
<TextView
    android:layout_width="20dp"
    android:layout_height="wrap_content"
    android:layout_columnWeight="0.5"
    android:layout_column="0"
    android:text="Label with some long text event more text"/>
<EditText
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:layout_columnWeight="1.5"
    android:inputType="textMultiLine"
    android:layout_column="1"
    android:text="Some really long text here and more and more and more ....  "
    android:layout_gravity="fill_horizontal"/>

我们在这里所做的只是为您的孩子(TextView 和 EditText)设置一些硬编码值,关于他们的 android:layout_width 属性,并给他们 android:layout_columnWeight 属性。这将设置您的列的一些比例(使用此值只是为了根据您的需要进行设置)。

使用 EditText,我们也在做一些小的事情 (android:inputType="textMultiLine") 只是为了确保您的文本将被包裹在多行中。

顺便说一句:如果您正在做一些输入表单,我建议您使用其他 ViewGroups,例如 LinearLayout。

感谢有任何问题请评论。

【讨论】:

  • 感谢您的回复。该示例被删减以专注于问题,这就是它过于简单的原因。问题的评论中指出了解决方案,即将layout_width设置为0dp。
  • 我不知道为什么当你在做同样的事情来解决问题(将 0dp 设置为你的宽度 attr)时,你为什么给我这个响应 -1,但是为什么我不能做任何事情那。收到反对票我的回答没有错
  • 我没有选择你的答案是正确的,因为它使用固定的宽度,这不会提供所需的结果来填充屏幕的宽度但不会掉出边缘。
  • 我不需要我的回答被接受,我只是想在这种情况下帮助你,我收到了不正确的反对票,因为我的回答肯定有效。我敢肯定你甚至没有尝试我的 xml :),因为如果你这样做了,你会看到一切正常,关键部分不仅是我的固定宽度,而且 layout_columnWeight 也是如此,在这种情况下,固定宽度只是破解 layout_columnWeight正在发挥重要作用,它控制第 0 列的数量和第 1 列的数量。这是我对这个案子的最后一次赞扬。好看。
猜你喜欢
  • 2021-10-23
  • 1970-01-01
  • 1970-01-01
  • 2017-10-23
  • 2020-12-19
  • 2014-08-02
  • 2012-03-19
  • 2021-04-21
  • 2016-02-04
相关资源
最近更新 更多