Listview выбирает несколько элементов при нажатии

1

Я пытаюсь создать диспетчер задач, и у меня есть только одна проблема. У меня есть список, который накачивается. Все элементы в списке правильно. Проблема в том, что когда я выбираю элемент, listview выберет другой элемент. Я слышал, что список просматривает список, поскольку он прокручивает вниз, чтобы сохранить память. Я думаю, что это может быть какая-то проблема. Вот картина проблемы. Если бы у меня было больше загруженных приложений, тогда он продолжал бы выбирать несколько раз.

Вот код моего адаптера и активности и связанный с XML

public class TaskAdapter extends BaseAdapter{
private Context mContext;
private List<TaskInfo> mListAppInfo;
private PackageManager mPack;


public TaskAdapter(Context c, List<TaskInfo> list, PackageManager pack) {
    mContext = c;
    mListAppInfo = list;
    mPack = pack;
}

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

@Override
public Object getItem(int position) {
    return mListAppInfo.get(position);
}

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

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    TaskInfo entry = mListAppInfo.get(position);


    if (convertView == null)
    {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        //System.out.println("Setting LayoutInflater in TaskAdapter " +mContext +" " +R.layout.taskinfo +" " +R.id.tmbox);
        convertView = inflater.inflate(R.layout.taskinfo,null);
    }

        ImageView ivIcon = (ImageView)convertView.findViewById(R.id.tmImage);
        ivIcon.setImageDrawable(entry.getIcon());

        TextView tvName = (TextView)convertView.findViewById(R.id.tmbox);
        tvName.setText(entry.getName());

        convertView.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v) {
                final CheckBox checkBox = (CheckBox)v.findViewById(R.id.tmbox);
                if(v.isSelected())
                {
                    System.out.println("Listview not selected ");
                    //CK.get(arg2).setChecked(false);
                    checkBox.setChecked(false);
                    v.setSelected(false);
                }
                else
                {
                    System.out.println("Listview selected ");
                    //CK.get(arg2).setChecked(true);
                    checkBox.setChecked(true);
                    v.setSelected(true);
                }

            }
        });

    return convertView;




public class TaskManager extends Activity implements Runnable
    {
private ProgressDialog pd;
private TextView ram;
private String s;

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.taskpage);
        setTitleColor(Color.YELLOW);

        Thread thread = new Thread(this);
        thread.start();

    }
    @Override
    public void run() 
    {
        //System.out.println("In Taskmanager Run() Thread");
        final PackageManager pm = getPackageManager();
        final ListView box = (ListView) findViewById(R.id.cBoxSpace);
        final List<TaskInfo> CK = populate(box, pm);
        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                ram.setText(s);
                box.setAdapter(new TaskAdapter(TaskManager.this, CK, pm));

                //System.out.println("In Taskmanager runnable Run()");    
                endChecked(CK);
            }
        });
                handler.sendEmptyMessage(0);
    }

Taskinfo.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" 
android:gravity="center_horizontal">

<ImageView 
    android:id="@+id/tmImage"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:scaleType="centerCrop"
    android:adjustViewBounds="false"
    android:focusable="false" />
<CheckBox 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:id="@+id/tmbox"
    android:lines="2"/>
      </LinearLayout>

Taskpage.xml

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
    <ListView
        android:id="@+id/cBoxSpace"
        android:layout_width="wrap_content"
        android:layout_height="400dp"
        android:orientation="vertical"/>
<TextView
        android:id="@+id/RAM"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp" />
<Button
        android:id="@+id/endButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="End Selected Tasks" />
</LinearLayout>

Любые идеи, по какой причине элементы, выбранные mutliple, выбираются одним щелчком мыши, были бы высоко оценены. Я возился с различными реализациями, слушателями и списками, но безрезультатно.

  • 1
    Если выбрано несколько элементов, происходит ли множественный выбор с элементами, видимыми на экране, или только при прокрутке?
  • 0
    Извините, я не хотел редактировать ваше сообщение, имел в виду редактировать мое>. <Я объяснил ответ в редактировании
Теги:
listview
android-listview

3 ответа

1

Я думаю, дело в том, что вы сохраняете только состояние проверки в представлении (v.setSelected).

И вы повторно используете это представление, поэтому его флажок всегда не меняет свое состояние.

Вы можете создать массив состояний для сохранения каждого состояния проверки каждого TaskInfo и проверить этот массив при создании представления.

например

// default is false
ArrayList<Boolean> checkingStates = new ArrayList<Boolean>(mListAppInfo.size());
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    TaskInfo entry = mListAppInfo.get(position);
    if (convertView == null)
    {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        convertView = inflater.inflate(R.layout.taskinfo,null);
    }

    ImageView ivIcon = (ImageView)convertView.findViewById(R.id.tmImage);
    ivIcon.setImageDrawable(entry.getIcon());

    TextView tvName = (TextView)convertView.findViewById(R.id.tmbox);
    tvName.setText(entry.getName());

    final CheckBox checkBox = (CheckBox)v.findViewById(R.id.tmbox);
    checkBox.setChecked(checkingStates.get(position));
    convertView.setSelected(checkingStates.get(position));

    convertView.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v) {
            if(v.isSelected())
            {
                System.out.println("Listview not selected ");
                //CK.get(arg2).setChecked(false);
                checkBox.setChecked(false);
                v.setSelected(false);
                checkingStates.get(position) = false;
            }
            else
            {
                System.out.println("Listview selected ");
                //CK.get(arg2).setChecked(true);
                checkBox.setChecked(true);
                v.setSelected(true);
                checkingStates.get(position) = true;
            }

        }
    });

return convertView;
}
1

Я не уверен на 100%, что вы пытаетесь сделать, но часть вашей проблемы может быть связана с условием в методе onClick:

if(v.isSelected())

Я думаю, вы хотите, чтобы это прочитало

if(v.isChecked())

isSelected наследуется от View, и это означает что-то отличное от isChecked

Кроме того, проверяется ли CheckBox или нет, не зависит от вашей модели данных, поскольку она является переработанным представлением. Ваш CheckBox должен быть проверен на основе entry (я предполагаю, что ваш класс TextInfo имеет метод isChecked() который возвращает логическое значение:

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    TaskInfo entry = mListAppInfo.get(position);

    if (convertView == null)
    {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        //System.out.println("Setting LayoutInflater in TaskAdapter " +mContext +" " +R.layout.taskinfo +" " +R.id.tmbox);
        convertView = inflater.inflate(R.layout.taskinfo,null);
    }

    ImageView ivIcon = (ImageView)convertView.findViewById(R.id.tmImage);
    ivIcon.setImageDrawable(entry.getIcon());

    TextView tvName = (TextView)convertView.findViewById(R.id.tmbox);
    tvName.setText(entry.getName());

    CheckBox checkBox = (CheckBox)v.findViewById(R.id.tmbox);
    checkBox.setChecked(entry.isChecked());
}

Я не думаю, что вам нужен View.OnClickListener вы convertView к convertView. Вы должны обработать это в OnItemClickListener подключенном к ListView. Предположим, что ваш ListView называется listView и TaskInfo экземпляры имеют setChecked и isChecked методы:

listView.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView parent, View v, int position, long id) {
        entry = mListAppInfo.get(position);
        entry.setChecked(!entry.isChecked());
    }
});
0
First of all don't set the list checked or unchecked on view position.
because view position means only visible items position in your listview but you would like to set checked or uncheked status on a particular list item. 

that why this problem arising in your code.


You have the need to set the items checked and unchecked on your custom arraylist getter setter like the code i have attached below:


package com.app.adapter;



public class CategoryDynamicAdapter {

    public static ArrayList<CategoryBean> categoryList = new ArrayList<CategoryBean>();

    Context context;
    Typeface typeface;
    public static String videoUrl = "" ;    
    Handler handler;
    Runnable runnable;


      // constructor
      public CategoryDynamicAdapter(Activity a, Context context, Bitmap [] imagelist,ArrayList<CategoryBean> list) {

        this.context    = context;
        this.categoryList       = list;
        this.a = a;


    }

     // Baseadapter to the set the data response from web service into listview.
     public BaseAdapter mEventAdapter  = new BaseAdapter() {



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

        @Override
        public Object getItem(int position) {
            return categoryList.get(position);
        }

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

        class ViewHolder {
            TextView    title,category,uploadedBy;
            ImageView   image;
            RatingBar video_rating;
            Button  report_video ,Flag_video;
        }

        public View getView(final int position, View convertView, final ViewGroup parent) {
            ViewHolder  vh = null ;

                if(convertView  ==  null) {

                vh                    =         new                                                          ViewHolder();  
                convertView           =         LayoutInflater.from(context).inflate (R .layout.custom_category_list_layout,null,false);
                vh.title              =         (TextView)                convertView                .findViewById        (R.id.title);
                vh.image = (ImageView)          convertView.findViewById(R.id.Imagefield);

                convertView.setTag(vh);
            }
            else 
            {
                vh=(ViewHolder) convertView.getTag();
            }   

            try
            {
                final CategoryBean Cb = categoryList.get(position);


//pay attention to code below this line i have shown here how to select a listview using arraylist getter setter objects 

                String checkedStatus   =   Cb.getCheckedStringStaus();
            if(checkdStatus.equal("0")
              { 
                   System.out.println("Listview not selected ");
                    //CK.get(arg2).setChecked(false);
                    checkBox.setChecked(false);
                    v.setSelected(false);
              }
                else             ////checkdStatus.equal("1")
                {
                    System.out.println("Listview selected ");
                    //CK.get(arg2).setChecked(true);
                    checkBox.setChecked(true);
                    v.setSelected(true);
                }

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

Ещё вопросы

Сообщество Overcoder
Наверх
Меню