ListView的Item对应多布局,滚动错位

在Android开发中,当ListView需要对应多种布局时,可能出现滚动错位的问题。常规做法是在Adapter的getView方法内判断并设置布局,但这可能导致数据错位。正确的解决方案是重写BaseAdapter的getItemViewType()和getViewTypeCount()方法,确保布局正确对应,避免滚动时的数据混乱。
摘要由CSDN通过智能技术生成

我相信肯定有不少人和我一样需要做到这样一个效果,一个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"
       
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值