列表视图中的所选项目无效

时间:2014-08-23 22:29:11

标签: android listview android-checkbox

基于http://lalit3686.blogspot.in/2012/06/today-i-am-going-to-show-how-to-deal.html,这是我的getView:

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

    final Model m = getItem(position);

    final ViewHolder viewHolder;
    /* convertView will be null if convertView isn't from recycler
     */
    if(convertView == null) {
        Log.d("SELECT_ADAPTER", "convertView is null; Position=" + position + " and " +
              " model=" + m.getTitle());
        LayoutInflater inflater = LayoutInflater.from(getContext());
        convertView = inflater.inflate(R.layout.selection_item, parent, false);

        // inflate individual views and cache them into viewholder
        viewHolder = new ViewHolder();

        viewHolder.cb = (CheckBox) convertView.findViewById(R.id.cb);
        viewHolder.cb.setChecked(m.isSelected());
        viewHolder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int getPosition = (Integer) buttonView.getTag();
                allModels.get(getPosition).setSelected(buttonView.isChecked());
            }
        });


        viewHolder.pictureIV = (ImageView) convertView.findViewById((R.id.Picture));
        viewHolder.playBtnIV = (ImageView) convertView.findViewById((R.id.ivPlayBtn));

        // associate view memory with these views
        convertView.setTag(viewHolder);

        convertView.setTag(R.id.cb, viewHolder.cb);

    }
    else {
        Log.d("SELECT_ADAPTER", "Reusing convertView, position=" + position + "and " +
               " model=" + model.getTitle());
        viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.cb.setTag(position);
    viewHolder.cb.setChecked(allModels.get(position).isSelected());
    // associate play button with model so listener callback knows which video to launch
    viewHolder.playBtnIV.setTag(m);

    // set values in views
    ImageLoader.getInstance().displayImage(m.getImageUrl(), viewHolder.pictureIV);

    return convertView;
}

当我点击活动A中的一个按钮时,我会浏览所有模型,并根据前面提到的监听器中设置的标志,创建一个" selected"像这样的模型实例:

public void onClickResultsBtn(View v) throws Exception {   
    for (MyModel m: allModels) {
        if (m.isSelected()) 
            selectedModels.add(m);
    }
.... 

然后启动活动B.当我按回活动B返回活动A时,我覆盖活动A的onResume以清除此选定的模型列表,这样如果我编辑我的选择,所选的模型列表将被正确更新,并且不包含重复的最后一次按下按钮:

@Override
public void onResume() {
    super.onResume();
    if(results != null && results.size() > 0) {
        results.clear();
        selectedModels.clear();
    }
}

如果我按回活动B并在活动A中编辑我的选择,则selectedModels列表不正确(我看到额外的值)。

0 个答案:

没有答案