为什么我的列表视图在滚动时更改项目背景颜色?

Why my listview change item background color while scrolling?

我将 BaseAdapter 用于我的列表视图。 我有以下代码:

public class ListViewAdapter extends BaseAdapter {

private Context mContext;
private ArrayList<JSONObject> arrayList;
private GetterSetter getterSetter = new GetterSetter();

public ListViewAdapter(Context context, ArrayList arrayList, Bundle bundle) {
    this.mContext = context;
    this.arrayList = arrayList;

    this.bundle = bundle;
}

@Override
public int getCount() {
    return arrayList.size();
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public Object getItem(int position) {
    return null;
}

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

    if (convertView == null) {
        LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        convertView = layoutInflater.inflate(R.layout.list_item, null);
    }

    TextView nameTextView = convertView.findViewById(R.id.textview_book_name);
    LinearLayout linearLayout = convertView.findViewById(R.id.item);

    JSONObject jsonObject = arrayList.get(position);

    try {

        String title = jsonObject.getString("title");
        String _id = jsonObject.getString("_id");

        nameTextView.setText(title);

        if(getterSetter.ifExists(_id)){
            linearLayout.setBackgroundColor(Color.parseColor("#397EAD"));
            nameTextView.setTextColor(Color.WHITE);
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

    return convertView;
}

}

GetterSetter 中的 ifExists 方法 Class:

public Boolean ifExists(String _id){

    if (myList != null) {
        for (int i=0;i<myList.size();i++){

            try {

                JSONObject jsonObject = myList.get(i);

                if(_id.equals(jsonObject.getString("_id"))){
                    return true;
                }

            } catch (JSONException e){}

        }
    }

    return false;

}

项目布局:

<?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="match_parent"
android:id="@+id/item" >

<TextView
    android:id="@+id/textview_book_name"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="35dp"
    android:textSize="18sp"
    android:textColor="#000000" />

我的列表视图运行良好,但如果我滚动它,每个项目都会突然改变颜色。 我希望项目具有 RGB 颜色:#397EAD 如果他的 _id 存在于另一个 class 的静态 ArrayList 中。我怎样才能做到这一点?如何解决滚动时更改颜色的问题?

在 xml 文件 android:background="#397EAD" 中设置背景颜色,如果没有帮助在 ListView xml 中设置相同的行

您没有处理 convertView 回收。如果颜色存在于列表中,您正在设置颜色,但如果列表中不存在,您需要一个 else 块将它们设置回默认值:

if(getterSetter.ifExists(_id)){
    linearLayout.setBackgroundColor(Color.parseColor("#397EAD"));
    nameTextView.setTextColor(Color.WHITE);
} else {
    // reset linearLayout and nameTextView colors to default here
}