我相信肯定有不少人和我一样需要做到这样一个效果,一个ListView需要对用多个布局,就是类似与QQ的聊天页面一样,是对应的两种布局,这样的情况下能想到的当然就是在Adapter里的getView方法的地方通过判断来选择使用哪一种布局,这种想法是没有错的,但是实际应用的时候却会出现一定问题,比如我滚动ListView的时候原来应该用1布局的那个Item结果用的布局2,造成ListView上的数据错位
下面先看看正常的写法,以及会造成的现象。
新建一个项目叫TestListViewDemo,然后将MainActivity对应的布局文件修改如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ListView
android:id="@+id/MainActivity_ListView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</RelativeLayout>
可以看到只有一个ListView,然后这个ListView会对应两种布局,那么就需要来写两种布局:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center|left"
android:orientation="horizontal"
android:paddingBottom="20dp"
android:paddingTop="20dp" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/listviwe_item_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"