美文网首页安卓开发
ListView中inflate出来的item的parent设置

ListView中inflate出来的item的parent设置

作者: 手指乐 | 来源:发表于2019-08-23 11:11 被阅读2次
  • 如果设置为null,根布局设置的高度是不起作用的,即使根布局是一个控件,比如:
<?xml version="1.0" encoding="utf-8"?>
<TextView android:layout_width="match_parent"
    android:layout_height="200dp"
    android:text="abc"
    xmlns:android="http://schemas.android.com/apk/res/android" />

这时200dp不起作用,而是根据里面的文字大小来决定item的高度,比如如下起作用:

<TextView android:layout_width="match_parent"
    android:layout_height="200dp"
    android:text="abc"
    android:textSize="200dp"
    xmlns:android="http://schemas.android.com/apk/res/android" />
  • 根布局是一个layout的情况下,根部局的高度也不起作用,而是里面子控件的高度起作用,比如下面item的高度是100dp:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="300dp">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="abc"/>
</RelativeLayout>
  • 如果里面的内容设置为match_parent,效果跟第一个一样,根据文字大小来决定item高度,因为parent设置的高度没用,所以里面子空间match_parent也没用:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="300dp">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="abc"/>

 </RelativeLayout>
  • 总结:设置为null时,因为没有父亲,根布局的layout_height没有作用,子布局的layout_height为绝对值时有用,为相对值(match_parent,wrap_content)时没用,里面内容的高度决定了item的高度(根布局为普通控件时,控件内容决定item高度,根布局为layout时,子控件设置的绝对高度或子控件的内容决定item高度)

  • 如果parent设置为getview传入的parent(第三个参数false),则根布局设置的高度就有用了,比如上面第一个就是200dp了

  • 如果这时候,根部局设置为match_parent,则根据里面内容来适配,比如以下item高度跟上面第一个一样,为文字的高度:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="abc"/>

</RelativeLayout>

以下高度变成了200dp:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:text="abc"/>

</RelativeLayout>
  • 另外,在as中如果把null变成非null,某些情况下,可能要重新编译才能看到效果(rebuild),直接run可能还是跟之前一样

相关文章

网友评论

    本文标题:ListView中inflate出来的item的parent设置

    本文链接:https://www.haomeiwen.com/subject/tvezsctx.html