Android GridLayout fill_horizo​​ntal离屏

时间:2016-08-29 11:37:31

标签: android grid-layout android-gridlayout

我有一个简单的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的图像,但在设备上运行时也是如此)。

enter image description here

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

1 个答案:

答案 0 :(得分:0)

我不确定为什么你需要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”),只是为了确保你的文字将被包裹在多行上。

BTW:如果你正在做一些输入表格,我会建议你使用像LinearLayout这样的其他ViewGroup。

感谢任何问题,请发表评论。

相关问题