Несколько SeekBar в адаптере, только последние обновления SeekBar

У меня есть ListView, в каждой строке которого есть SeekBar. размер списка и, следовательно, количество SeekBars будут варьироваться.

Я установил SeekBar.OnSeekBarChangeListener и, исходя из этого, обновляю TextView на основе целого числа, отображаемого SeekBar.

Проблема в том, что только последний SeekBar в списке обновляется из SeekBar.OnSeekBarChangeListener.

Как заставить работать все SeekBars?

Заранее спасибо.

private class MySimpleArrayAdapter extends ArrayAdapter<String> {
        private final Context context;
        private final ArrayList<?> list;            

        public MySimpleArrayAdapter(Context context, ArrayList<?> list) {

            super(context, R.layout.monitoringrowlayout);
            Log.e(TAG, "inside adapter constructor");
            this.context = context;
            this.list = list;               

        }

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

            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View rowView = inflater.inflate(R.layout.monitoringrowlayout, parent, false);

            final int pos = position;               

            Log.e(TAG, "list size in adapter = " + list.size());

            String record = list.get(position).toString();
            rowView.setTag(record);
            String[] itemsInRecord = record.split(",");
            Log.e(TAG, "itemin record = " + itemsInRecord.length);
            String[] recordItem = new String[itemsInRecord.length];

            for (int x = 0; x < itemsInRecord.length; x++) {

                recordItem[x] = itemsInRecord[x];

                Log.e(TAG, "recordItem[x]" + x + " " +recordItem[x] );

            }

            recordItem[0] = recordItem[0].replace('[', ' ').trim();     
            recordItem[3] = recordItem[3].replace(']', ' ').trim(); 

            TextView description =  (TextView) rowView.findViewById(R.id.rowmonitoringdescription);
            description.setText(recordItem[1]);

            rating =  (TextView) rowView.findViewById(R.id.rowmonitoringrating);                

            sb = (SeekBar)rowView.findViewById(R.id.seekbarmonitoring);
            sb.setOnSeekBarChangeListener(customSeekBarListener);

            return rowView;

        }

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

    }// end of adapter class

private SeekBar.OnSeekBarChangeListener customSeekBarListener = new SeekBar.OnSeekBarChangeListener() {

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

        upDateTextBox(progress);

    }
};    

private void upDateTextBox(int progress){

    rating.setText(String.valueOf(progress));       

}

person turtleboy    schedule 25.01.2016    source источник
comment
очевидно, потому что вы устанавливаете rating (тот, который используется для upDateTextBox) var в getView... поэтому rating всегда будет TextView из последнего вызова getView... очевидно, вам нужно подключить панель поиска с текстовым представлением... общий способ - используйте setTag для панели поиска со ссылками TextView   -  person Selvin    schedule 25.01.2016
comment
взгляните на мой ответ   -  person Iamat8    schedule 25.01.2016
comment
кажется, что только последний SeekBar в списке обновляется из SeekBar.OnSeekBarChangeListener — пожалуйста, объясните, что именно это означает. Если вы имеете в виду, что обновляется только один rating, это то, на что ссылается Селвин.   -  person CommonsWare    schedule 25.01.2016
comment
... также есть еще одна проблема с этим кодом ... AdapterView повторно использует представления элемента ... с таким кодом вы не сможете получить правильные значения после прокрутки элемента из видимых элементов и обратно   -  person Selvin    schedule 25.01.2016


Ответы (1)


Очевидно, это должно было случиться.

Так как sb всегда будет "последним" SeekBar, а rating всегда будет "последним" рейтингом TextView.

Измените свой код:

    private class MySimpleArrayAdapter extends ArrayAdapter<String> {
    private final Context context;
    private final ArrayList<?> list;


    public MySimpleArrayAdapter(Context context, ArrayList<?> list) {

        super(context, R.layout.monitoringrowlayout);
        Log.e(TAG, "inside adapter constructor");
        this.context = context;
        this.list = list;


    }

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


        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View rowView = inflater.inflate(R.layout.monitoringrowlayout, parent, false);

        final int pos = position;


        Log.e(TAG, "list size in adapter = " + list.size());



        String record = list.get(position).toString();
        rowView.setTag(record);
        String[] itemsInRecord = record.split(",");
        Log.e(TAG, "itemin record = " + itemsInRecord.length);
        String[] recordItem = new String[itemsInRecord.length];

        for (int x = 0; x < itemsInRecord.length; x++) {

            recordItem[x] = itemsInRecord[x];

            Log.e(TAG, "recordItem[x]" + x + " " +recordItem[x] );

        }

        recordItem[0] = recordItem[0].replace('[', ' ').trim();
        recordItem[3] = recordItem[3].replace(']', ' ').trim();

        TextView description =  (TextView) rowView.findViewById(R.id.rowmonitoringdescription);
        description.setText(recordItem[1]);



        SeekBar sb = (SeekBar)rowView.findViewById(R.id.seekbarmonitoring);
        sb.setOnSeekBarChangeListener(customSeekBarListener);
        sb.setTag(rowView.findViewById(R.id.rowmonitoringrating));






        return rowView;




    }

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

}// end of adapter class



    private SeekBar.OnSeekBarChangeListener customSeekBarListener = new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            upDateTextBox((TextView) seekBar.getTag(), progress);

        }
    };


    private void upDateTextBox(TextView tv, int progress){

        tv.setText(String.valueOf(progress));


    }
}
person Nem    schedule 25.01.2016
comment
Спасибо за Ваш ответ. Могу я спросить вас, как мне передать 2 значения String, recordItem [0] и recordItem [3] в getView для updateTextBox? - person turtleboy; 25.01.2016