2

Я использую ViewHolder в адаптере, вот два основных метода и класса:

static class ViewHolder {
    public TextView textView1Form1;
    public TextView textView2Form1;
    public TextView textView3Form1;
    public TextView textView1Form2;
    public TextView textView2Form2;
    public TextView textView3Form2;
    public TextView textView4Form2;
    public TextView textView5Form2;
    public LinearLayout linearLayout_1;
    public LinearLayout linearLayout_2;
}

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

    final ViewHolder holder;
    int type = getItemViewType(position);

    if (convertView == null) {
        holder = new ViewHolder();

        switch (type) {
            case FIRST_WORDS:
                convertView = mInflater.inflate(R.layout.row_words_form_1, null, true);

                holder.textView1Form1 = (TextView) convertView.findViewById(R.id.text_1);
                holder.textView2Form1 = (TextView) convertView.findViewById(R.id.text_2);
                holder.textView3Form1 = (TextView) convertView.findViewById(R.id.text_3);

                holder.linearLayout_1 = (LinearLayout) convertView.findViewById(R.id.linearLayout_1);
                break;
            case SECOND_WORDS:
                convertView = mInflater.inflate(R.layout.row_words_form_2, null, true);

                holder.textView1Form2 = (TextView) convertView.findViewById(R.id.text_1);
                holder.textView2Form2 = (TextView) convertView.findViewById(R.id.text_2);
                holder.textView3Form2 = (TextView) convertView.findViewById(R.id.text_3);
                holder.textView4Form2 = (TextView) convertView.findViewById(R.id.text_4);
                holder.textView5Form2 = (TextView) convertView.findViewById(R.id.text_5);

                holder.linearLayout_2 = (LinearLayout) convertView.findViewById(R.id.linearLayout_2);
                break;
        }
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    switch (type){
        case FIRST_WORDS:
            holder.textView1Form1.setText(mWordsForm1[position][0]);
            holder.textView2Form1.setText(mWordsForm1[position][1]);
            holder.textView3Form1.setText(mWordsForm1[position][2]);
            break;
        case SECOND_WORDS:
            holder.textView1Form2.setText(mWordsForm2[position - FIRST_ARRAY_LENGTH][0]);
            holder.textView2Form2.setText(mWordsForm2[position - FIRST_ARRAY_LENGTH][1]);
            holder.textView3Form2.setText(mWordsForm2[position - FIRST_ARRAY_LENGTH][2]);
            holder.textView3Form2.setText(mWordsForm2[position - FIRST_ARRAY_LENGTH ][3]);
            holder.textView3Form2.setText(mWordsForm2[position - FIRST_ARRAY_LENGTH][4]);
            break;
    }
    return convertView;
}

Я столкнулся с проблемой, что не могу изменить background только одного элемента. Сразу меняется несколько (один на экране, а остальные дальше, за пределами списка, который на экране). Из-за этого возник вопрос: а почему я меняю что-либо в статических переменных класса ViewHolder, а не загружаю их в контейнер и меняю уже там?


Полный код второго switch:

switch (type){
            case FIRST_WORDS:
                holder.textView1Form1.setText(mWordsForm1[position][0]);
                holder.textView2Form1.setText(mWordsForm1[position][1]);
                holder.textView3Form1.setText(mWordsForm1[position][2]);
                if (holder.linearLayout_1 == null) Log.i(TAG, MSG + "ll_1 null");
                holder.linearLayout_1.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (event.getAction() == MotionEvent.ACTION_DOWN) {
                            timer = new HoldTimer(500, 100);
                            timer.start();

                            holder.textView1Form1.setBackgroundColor(mContext.getResources().getColor(R.color.red));
                            holder.textView2Form1.setBackgroundColor(mContext.getResources().getColor(R.color.red));
                            holder.textView3Form1.setBackgroundColor(mContext.getResources().getColor(R.color.red));

                            return true;
                        } else if (event.getAction() == MotionEvent.ACTION_UP) {
                            timer.cancel();

                            holder.textView1Form1.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                            holder.textView2Form1.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                            holder.textView3Form1.setBackgroundColor(mContext.getResources().getColor(R.color.white));

                            return true;
                        }
                        return false;
                    }
                });
                break;

            case SECOND_WORDS:
                holder.textView1Form2.setText(mWordsForm2[position - FIRST_ARRAY_LENGTH][0]);
                holder.textView2Form2.setText(mWordsForm2[position - FIRST_ARRAY_LENGTH][1]);
                holder.textView3Form2.setText(mWordsForm2[position - FIRST_ARRAY_LENGTH][2]);
                holder.textView3Form2.setText(mWordsForm2[position - FIRST_ARRAY_LENGTH ][3]);
                holder.textView3Form2.setText(mWordsForm2[position - FIRST_ARRAY_LENGTH][4]);
                if (holder.linearLayout_2 == null) Log.i(TAG, MSG + "ll_2 null");
                holder.linearLayout_2.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (event.getAction() == MotionEvent.ACTION_DOWN) {
                            timer = new HoldTimer(500, 100);
                            timer.start();

                            holder.textView1Form2.setBackgroundColor(mContext.getResources().getColor(R.color.red));
                            holder.textView2Form2.setBackgroundColor(mContext.getResources().getColor(R.color.red));
                            holder.textView3Form2.setBackgroundColor(mContext.getResources().getColor(R.color.red));
                            holder.textView4Form2.setBackgroundColor(mContext.getResources().getColor(R.color.red));
                            holder.textView5Form2.setBackgroundColor(mContext.getResources().getColor(R.color.red));

                            return true;
                        } else if (event.getAction() == MotionEvent.ACTION_UP) {
                            timer.cancel();

                            holder.textView1Form2.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                            holder.textView2Form2.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                            holder.textView3Form2.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                            holder.textView4Form2.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                            holder.textView5Form2.setBackgroundColor(mContext.getResources().getColor(R.color.white));

                            return true;
                        }
                        return false;
                    }
                });
                break;
        }

Если нажать и отпустить, тогда все хорошо, а вот если протянуть, тогда и Action up не срабатывает (для такого случая, добавлю слушатель передвижения по y), и где-то внизу появляется очередная линия. А if ... else тут не впихнуть, как написал ermak0ff.

1 ответ 1

4

Я столкнулся с проблемой, что не могу изменить background только одного элемента. Сразу меняется несколько

Данное поведение наблюдается в связи с переиспользованием convertView.

Как вариант необходимо при изменении какого либо background всегда иметь "background по умолчанию"

Предположим, реализовали мы наш adapter так:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        ...
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    ...
    if(some_condition){
        convertView.setBackgroundColor(Color.RED);
    }
    ...
}

В приведенном примере все хорошо до момента появления первого элемента с красным bg. После пролистывания которого, цвет будет "перебегать" ввиду того, что сам convertView переиспользуется.

Следовательно надо устанавливать bg по умолчанию.

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        ...
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    ...

    if(some_condition){
        convertView.setBackgroundColor(Color.RED);
    } else {
        convertView.setBackgroundColor(Color.DEFAULT);
    }
    ...
}
14
  • Ну... У меня есть одна загвоздка... :( Сейчас выложу.
    – user189127
    6 ноя 2015 в 21:39
  • На вопрос Вы ответили, но можете что-то сказать про обновленный вопрос?
    – user189127
    6 ноя 2015 в 21:52
  • @bukashka101 а selector не пробовали прикрутить и не париться с setOnTouchListener?
    – ermak0ff
    7 ноя 2015 в 8:01
  • Мне его уже pavlofff предлагал, но увы 1 он не подходит. У меня одна разметка, а в ней 5 View, так что по id у ним не обратиться, а значит selector не подойдет (по крайней мере, я так понял).
    – user189127
    7 ноя 2015 в 11:50
  • @bukashka101 ну так а если селектор повесить только на view-контейнет...или Вам нужно что бы там при нажатии каждый TextView пестрил цветами радуги))
    – ermak0ff
    7 ноя 2015 в 12:42

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.