Почему мой список меняет цвет фона элемента при прокрутке? - PullRequest
0 голосов
/ 26 февраля 2020

Я использую 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;
}

}

метод ifExists в классе GetterSetter:

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 существует в stati c ArrayList в другом классе. Как я могу это сделать? Как решить проблему с изменением цвета при прокрутке?

Ответы [ 2 ]

0 голосов
/ 26 февраля 2020

Вы не обрабатываете convertView переработку. Вы устанавливаете цвета, если они есть в списке, но вам нужен блок else, чтобы вернуть их к значениям по умолчанию, если их нет в списке:

if(getterSetter.ifExists(_id)){
    linearLayout.setBackgroundColor(Color.parseColor("#397EAD"));
    nameTextView.setTextColor(Color.WHITE);
} else {
    // reset linearLayout and nameTextView colors to default here
}
0 голосов
/ 26 февраля 2020

Установить цвет фона в xml файле android:background="#397EAD", если не поможет, установить ту же строку в ListView xml

...