【问题标题】:Checkbox unchecked when I scroll listview on Android当我在 Android 上滚动列表视图时复选框未选中
【发布时间】:2012-06-09 09:06:39
【问题描述】:

我是 Android 开发新手。我用textboxcheckbox 创建了一个listview

当我检查checkbox 并向下滚动以检查列表视图中的其他一些项目时,较旧的项目未被选中。

如何在listview 中避免这个问题?请用我的代码指导我。

代码如下:

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:id="@+id/TextView01"
        android:layout_height="wrap_content"
        android:text="List of items"
        android:textStyle="normal|bold"
        android:gravity="center_vertical|center_horizontal"
        android:layout_width="fill_parent"/>

    <ListView
        android:id="@+id/ListView01"
        android:layout_height="250px"
        android:layout_width="fill_parent"/>

    <Button
        android:text="Save"
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

这是我用来创建动态列表行的 XML 页面:

listview.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:gravity="left|center"
    android:layout_width="wrap_content"
    android:paddingBottom="5px"
    android:paddingTop="5px"
    android:paddingLeft="5px">

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="#FFFF00"
        android:text="hi"/>

    <TextView
        android:text="hello"
        android:id="@+id/TextView02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10px"
        android:textColor="#0099CC"/>

    <EditText
        android:id="@+id/txtbox"
        android:layout_width="120px"
        android:layout_height="wrap_content"
        android:textSize="12sp"
        android:layout_x="211px"
        android:layout_y="13px"/>

    <CheckBox
        android:id="@+id/chkbox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

这是我的活动课。

CustomListViewActivity.java:

public class CustomListViewActivity extends Activity {

    ListView lstView;
    static Context mContext;
    Button btnSave;

    private static class EfficientAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public EfficientAdapter(Context context) {
            mInflater = LayoutInflater.from(context);

        }

        public int getCount() {
            return country.length;
        }

        public Object getItem(int position) {
            return position;
        }

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

        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.listview, parent,
                        false);
                holder = new ViewHolder();
                holder.text = (TextView) convertView
                        .findViewById(R.id.TextView01);
                holder.text2 = (TextView) convertView
                        .findViewById(R.id.TextView02);
                holder.txt = (EditText) convertView.findViewById(R.id.txtbox);
                holder.cbox = (CheckBox) convertView.findViewById(R.id.chkbox1);

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

            holder.text.setText(curr[position]);
            holder.text2.setText(country[position]);
            holder.txt.setText("");
            holder.cbox.setChecked(false);

            return convertView;
        }

        public class ViewHolder {
            TextView text;
            TextView text2;
            EditText txt;
            CheckBox cbox;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        lstView = (ListView) findViewById(R.id.ListView01);
        lstView.setAdapter(new EfficientAdapter(this));
        btnSave = (Button)findViewById(R.id.btnSave);
        mContext = this;

        btnSave.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // I want to print the text which is in the listview one by one.
                // Later I will insert it in the database.
                //
                //            Toast.makeText(getBaseContext(), "EditText Value, checkbox value and other values", Toast.LENGTH_SHORT).show();
                for (int i = 0; i < lstView.getCount(); i++) {
                    View listOrderView;
                    listOrderView = lstView.getChildAt(i);
                    try{
                        EditText txtAmt = (EditText)listOrderView.findViewById(R.id.txtbox);
                        CheckBox cbValue = (CheckBox)listOrderView.findViewById(R.id.chkbox1);
                        if(cbValue.isChecked()== true){
                            String amt = txtAmt.getText().toString();
                            Toast.makeText(getBaseContext(), "Amount is :"+amt, Toast.LENGTH_SHORT).show();
                        }

                    }
                    catch (Exception e) {
                        // TODO: handle exception
                    }
                }

            }
        });
    }

    private static final String[] country = { "item1", "item2", "item3",
        "item4", "item5", "item6","item7", "item8", "item9",
        "item10", "item11", "item12" };

    private static final String[] curr = { "1", "2", "3", "4", "5", "6","7", "8", "9", "10", "11", "12" };
}

请帮我解决这个问题。

我在很多地方都提到过这个问题。但是我无法得到正确的答案来解决这个问题。

请提供代码以避免在上下滚动时取消选中复选框。

【问题讨论】:

    标签: android listview checkbox scroll


    【解决方案1】:

    在自定义列表视图适配器调用 setChecked 调用 setOnCheckedChangeListener

    这样你就可以从回收的视图中切断到旧监听器的链接。

    【讨论】:

    • 我知道这已经很老了,但你能详细说明一下吗? setChecked 带有什么参数。我打电话给false,滚动后它被取消选中。我们需要在这里维护选择数组还是什么。
    • 你好@Atul,有很多方法可以用checkbox维护listview,你可以使用数组或者更好的方法来使用sparsebooleanarray,你也可以参考这个lalit3686.blogspot.in/2012/06/…。谢谢...!!!
    • 好的。我得到了它。我们需要维护标志并从同一位置调用setChecked。顺便说一句,这个答案与this 相矛盾,它说我们应该打电话给setChecked 之前我们打电话给setOnCheckedChangeListener
    • 关于调用顺序这是正确的方法:stackoverflow.com/a/15523518/1911652
    • 是的,这是@Shade 给出的好答案
    【解决方案2】:

    您可以使用以下适配器代码在 ListView 中完美运行复选框。

    这里有一个详细的演示:Listview With Checkbox Android

    有关详细信息,请参阅详细的演示链接。它还显示了如何将检查的信息发送到下一个活动。

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.CheckBox;
    import android.widget.TextView;
    import android.widget.Toast;
    import java.util.ArrayList;
    
    
    public class CustomAdapter  extends BaseAdapter {
    
        private Context context;
        public static ArrayList<Model> modelArrayList;
    
        public CustomAdapter(Context context, ArrayList<Model> modelArrayList) {
    
            this.context = context;
            this.modelArrayList = modelArrayList;
        }
    
        @Override
        public int getViewTypeCount() {
            return getCount();
        }
    
        @Override
        public int getItemViewType(int position) {
            return position;
        }
    
        @Override
        public int getCount() {
            return modelArrayList.size();
        }
    
        @Override
        public Object getItem(int position) {
            return modelArrayList.get(position);
        }
    
        @Override
        public long getItemId(int position) {
            return 0;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
    
            if (convertView == null) {
                holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context
                         .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.lv_item, null, true);
    
                holder.checkBox = (CheckBox) convertView.findViewById(R.id.cb);
                holder.tvAnimal = (TextView) convertView.findViewById(R.id.animal);
    
                convertView.setTag(holder);
            }
            else {
                // The getTag returns the viewHolder object set as a tag to the view
                holder = (ViewHolder)convertView.getTag();
            }
    
            holder.checkBox.setText("Checkbox " + position);
            holder.tvAnimal.setText(modelArrayList.get(position).getAnimal());
    
            holder.checkBox.setChecked(modelArrayList.get(position).getSelected());
    
            holder.checkBox.setTag(R.integer.btnplusview, convertView);
            holder.checkBox.setTag( position);
            holder.checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    View tempview = (View) holder.checkBox.getTag(R.integer.btnplusview);
                    TextView tv = (TextView) tempview.findViewById(R.id.animal);
                    Integer pos = (Integer)  holder.checkBox.getTag();
                    Toast.makeText(context, "Checkbox " + pos + " clicked!", Toast.LENGTH_SHORT).show();
    
                    if (modelArrayList.get(pos).getSelected()){
                        modelArrayList.get(pos).setSelected(false);
                    }
                    else {
                        modelArrayList.get(pos).setSelected(true);
                    }
    
                }
            });
    
            return convertView;
        }
    
        private class ViewHolder {
    
            protected CheckBox checkBox;
            private TextView tvAnimal;
        }
    }
    

    Model

    public class Model {
    
        private boolean isSelected;
    
        private String animal;
    
        public String getAnimal() {
            return animal;
        }
    
        public void setAnimal(String animal) {
            this.animal = animal;
        }
    
        public boolean getSelected() {
            return isSelected;
        }
    
        public void setSelected(boolean selected) {
            isSelected = selected;
        }
    }
    

    【讨论】:

      【解决方案3】:

      在您的getView() 中有以下行

      holder.cbox.setChecked(false);
      

      每次调用 getView() 时都会取消选中 CheckBox(例如,当您滚动列表时)

      【讨论】:

      • 您好弗拉基米尔,感谢您的建议。我删除这条线并运行它。这次它没有取消选中该复选框。但是当我选择列表中的第一个和第二个项目并滚动时,会自动选择其他一些项目。我认为它指的是列表的位置,并在我上下滚动时自动检查。如何解决?
      • getView() 重用 convertView,因此如果 CheckBox 在某个位置被选中,它在重用时将保持选中状态。您需要找到一种方法来根据某些条件设置它的检查状态
      【解决方案4】:

      块引用

      **在侧边的 getView() 方法就这样调用>>

      check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
      
                  @Override
                  public void onCheckedChanged(CompoundButton arg0, boolean arg1) 
                  {
      
                      if(check.isChecked())
                      {
                          //checked
                          chkArray[position]=true;
                      }
                      else
                      {   //uncheck
                        chkArray[position]=false;
      
                      }
                  }
              });
      
      //check condition for checkboxes
              if(chkArray.length>0)
              {
                  for (int i = 0; i < chkArray.length; i++) 
                  {
                      if(chkArray[position]!=null && chkArray[position])
                      {
                          check.setChecked(true);
                      }
                  }
              }
      

      【讨论】:

      • getView 中使用循环是一种不好的做法
      【解决方案5】:

      考虑:

      holder.cbox.setChecked(false);
      

      删除此行。每次滚动列表视图时,都会调用 getView() 方法。

      【讨论】:

      • 您好 Panchal,感谢您的回复。我删除这条线并运行它。这次它没有取消选中该复选框。但是当我选择列表中的第一个和第二个项目并滚动时,会自动选择其他一些项目。我认为它是指列表的位置,并在我上下滚动时自动检查。
      【解决方案6】:

      我之前也遇到过这个问题。 Android 这样做是为了节省空间;仅加载了您当前看到的项目,这就是我发现的。

      如果您在列表的底部,则 id 1 可能位于第 5 位。我在网上搜索过,之前发现过这个。

      但是this 会帮助你:D

      【讨论】:

        【解决方案7】:

        我终于在几个小时后找到了解决方案,也就是

        1. 添加带有 set 和 get 方法的布尔变量数组类。
        2. 添加一个数组来保存我的选择。
        3. 使用 onClickListner。

        getView 方法内部如下:

        
        if(marray!=null) { //if myarray class object has data
        holder.name.setText(marray.getName());
        .
        .
        holder.checkbox.setChecked(marray.isChecked());//get the checkbox state 
        }
        

        将值赋给 holder.checkbox.setOnClickListener 方法中的布尔变量:

        
        holder.checkbox.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (allReport.UserSelection.contains(
        Integer.parseInt(marrays.get(position)
        .getIdd()))) // check if id selected before
                            {
              marray.setChecked(false);// marray is the object from myArray class
              allReport.UserSelection.remove(new Integer(Integer.parseInt(marrays.get(position).getIdd())));//remove id 
        
        
         }else{
               allReport.UserSelection.add(Integer.parseInt
                   (marrays.get(position).getIdd()));//save the selection 
                    marray.setChecked(true);//save the boolean to true}
        

        这为我解决了问题 我希望这会有所帮助

        【讨论】:

          【解决方案8】:

          它的解决方案是在adapter viewholder中增加itemView.OnClicklistener的变化。这肯定会解决你的职位问题

          【讨论】:

            【解决方案9】:

            当我们在列表视图中滚动项目时,它会从适配器恢复值。这就是未选中复选框的原因。但是,如果我们用最新值更新适配器,它将保持选中状态。为此,您需要使用 setOnClickListener()。

            您需要做的就是在单击复选框时更新您的适配器。您可以参考这个link 来了解一下

            【讨论】:

            • 避免仅链接的答案,请说明这个答案如何值得信任。
            • 当我们在列表视图中滚动项目时,它会从适配器恢复值。这就是未选中复选框的原因。但是,如果我们用最新值更新适配器,它将保持选中状态。为此,您需要使用 setOnClickListener()
            • 太好了,把上面的解释作为答案,将来可能会对某人有所帮助。
            猜你喜欢
            • 2016-09-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-01-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多