Android 列表视图在适配器中滚动时出现重复值

Android List View duplicate values on scroll in Adapter

我正在将数据绑定到 Android 中的列表视图控件。数据存储在 ArrayList 中。在适配器的 getView() 函数中,我得到了包含 23 个项目的整个列表。如果 'selectedval' 为“1”,我将值设置为行中的 TextView。

但是,尽管列表包含 23 个唯一值,但我在视图中看到了重复值。在调试时,我看到值在滚动时重复。

这是 getView() 函数的代码。

@SuppressLint("InflateParams")
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View mView = convertView;

    if (mView == null){
        mView = mInflator.inflate(R.layout.custom_rate_card, null);
        FancyTextview mTxtName = (FancyTextview)mView.findViewById(R.id.txt_list_name);
        FancyTextview mTxtPrice = (FancyTextview)mView.findViewById(R.id.txt_list_price);

        if(selectedVal == 0){
            String laundryPrice = mRateCardData.get(position).getLaundryPrice();
            if(Integer.parseInt(laundryPrice) != 0 && laundryPrice != null)
            {   
                mTxtName.setText(mRateCardData.get(position).getName());
                mTxtPrice.setText(laundryPrice);
            }
        }
        if(selectedVal == 1){
            String IPrice = mRateCardData.get(position).getIroningPrice();
            String Iname = mRateCardData.get(position).getName();
            if(Integer.parseInt(IPrice) != 0 && IPrice != null)
            {
                mTxtPrice.setText(IPrice);
                mTxtName.setText(Iname);
            }
        }
        return mView;
    }
    else{
        return mView;
    }
}

我搜索了一下,认为它与视图的回收有关。但是我一直无法解决。

如有任何帮助,我们将不胜感激。谢谢

您创建视图的方式不正确。仅当 convertView 为 null 时,您才需要扩充新视图,但每次调用 getView 时都需要设置数据。

我建议研究使用 Holder 模式:

您的代码应如下所示:

@SuppressLint("InflateParams")
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View mView = convertView;

    if (mView == null){
        mView = mInflator.inflate(R.layout.custom_rate_card, null);
        FancyTextview mTxtName = (FancyTextview)mView.findViewById(R.id.txt_list_name);
        FancyTextview mTxtPrice = (FancyTextview)mView.findViewById(R.id.txt_list_price);

     }
     if(selectedVal == 0){
        String laundryPrice = mRateCardData.get(position).getLaundryPrice();
        if(Integer.parseInt(laundryPrice) != 0 && laundryPrice != null)
        {   
            mTxtName.setText(mRateCardData.get(position).getName());
            mTxtPrice.setText(laundryPrice);
        }
    } else if (selectedVal == 1) {
        String IPrice = mRateCardData.get(position).getIroningPrice();
        String Iname = mRateCardData.get(position).getName();
        if(Integer.parseInt(IPrice) != 0 && IPrice != null)
        {
            mTxtPrice.setText(IPrice);
            mTxtName.setText(Iname);
        }
   }



   return mView;

}