自定义ListView复选框选择

时间:2016-10-06 02:20:16

标签: android listview

我正在尝试检查自定义listView项目的checkbox

我正在尝试在我的自定义列表视图适配器上使用view.setOnClickListener

当我选择listView项目中的一项时,另一项也会从列表中选择。

我的getView代码

 @Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View view = convertView;
    final ViewHolder holder;

    if (view == null){
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        view = inflater.inflate(row, parent, false);

        holder = new ViewHolder();

        holder.studentName = (TextView) view.findViewById(R.id.studentName);
        holder.id = (TextView) view.findViewById(R.id.studentID);
        holder.checkBox = (CheckBox) view.findViewById(R.id.checkBox);
        view.setTag(holder.checkBox);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!holder.checkBox.isChecked() && view!=null) {
                    holder.checkBox.setChecked(true);
                    presentStudent.add(data.get(position));
                    Toast.makeText(context, "added " + data.get(position).getName(), Toast.LENGTH_SHORT).show();
                }
                else {
                    holder.checkBox.setChecked(false);
                    presentStudent.remove(data.get(position));
                    Toast.makeText(context, "removed " + data.get(position).getName(), Toast.LENGTH_SHORT).show();
                }



            }
        });

        view.setTag(holder);

    } else {
        holder = (ViewHolder) view.getTag();
    }

    if((data == null) || ((position+1) > data.size()))
        return view;

    studentData = data.get(position);



    if ((holder.studentName != null) && null != studentData.getName()
            && studentData.getName().trim().length() > 0 )
        holder.studentName.setText(Html.fromHtml(studentData.getName()));

    if ((holder.id != null) && null != studentData.getAcademicId()
            && studentData.getAcademicId().trim().length() > 0 )
        holder.id.setText(Html.fromHtml(studentData.getAcademicId()));


    return view;
}

这是我的布局代码:

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


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">


        <TextView
            android:layout_marginBottom="10dp"
            android:text="ID: 20151057010 (057)"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/studentID"
            android:layout_alignBottom="@+id/checkBox"
            android:layout_alignLeft="@+id/studentName"
            android:layout_alignStart="@+id/studentName" />

        <ImageView

            android:layout_width="40dp"
            android:layout_height="40dp"
            android:id="@+id/image"
            android:src="@drawable/student_icon"
            android:layout_marginLeft="14dp"
            android:layout_marginStart="14dp"
            android:layout_centerVertical="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />

        <CheckBox
            android:focusable="false"
            android:focusableInTouchMode="false"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/checkBox"
            android:layout_below="@+id/studentName"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_marginRight="11dp"
            android:layout_marginEnd="11dp" />

        <TextView
            android:id="@+id/studentName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Sudarshan Mondal"
            android:textSize="20sp"
            android:layout_marginLeft="31dp"
            android:layout_marginStart="31dp"
            android:layout_alignTop="@+id/image"
            android:layout_toRightOf="@+id/image"
            android:layout_toEndOf="@+id/image"
            android:layout_marginTop="10dp"/>
    </RelativeLayout>


   </LinearLayout>

I have selected this item This item automatically get selected

我该怎么办?

4 个答案:

答案 0 :(得分:2)

这是因为listview的默认行为重用了膨胀的视图。采用临时arraylist来存储点击位置并验证相同的arraylist是否包含在getView方法中的特定位置。在适配器类中声明arraylist,在这里:

ArrayList<String> selectedPosition = new ArrayList<String>();

现在按照以下内容更新你的getView()方法:

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View view = convertView;
    final ViewHolder holder;

    if (view == null){
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        view = inflater.inflate(row, parent, false);

        holder = new ViewHolder();

        holder.studentName = (TextView) view.findViewById(R.id.studentName);
        holder.id = (TextView) view.findViewById(R.id.studentID);
        holder.checkBox = (CheckBox) view.findViewById(R.id.checkBox);
        //view.setTag(holder.checkBox); No need to do this

        view.setTag(holder);

    } else {
        holder = (ViewHolder) view.getTag();
    }

    if((data == null) || ((position+1) > data.size()))
        return view;

    studentData = data.get(position);



    if ((holder.studentName != null) && null != studentData.getName()
            && studentData.getName().trim().length() > 0 )
        holder.studentName.setText(Html.fromHtml(studentData.getName()));

    if ((holder.id != null) && null != studentData.getAcademicId()
            && studentData.getAcademicId().trim().length() > 0 )
        holder.id.setText(Html.fromHtml(studentData.getAcademicId()));

      //Added Change here...Check if arraylist contains selectedposition or not?

        if(selectedPosition.contains(String.valueOf(position))){
               holder.checkBox.setChecked(true);
               presentStudent.add(data.get(position));
        }else{
               holder.checkBox.setChecked(false);
               presentStudent.remove(data.get(position));
        }

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


           //Simply store and check selectedPosition

           if(selectedPosition.contains(String.valueOf(position)))
               selectedPosition.remove(String.valueOf(position));
           else
               selectedPosition.add(String.valueOf(position));

           //And then update adapter
           notifyDataSetChanged();

            }
        });


    return view;
}

答案 1 :(得分:0)

你已经添加了两次setTag(),肯定是搞乱了。在第一次执行setTag()时,您正在为复选框设置标记,但在执行getTag()时,您将获得完整的持有者。

编辑:

滚动时重复使用您的视图。 您必须为复选框实现checkedchangelistener并更新复选框状态:

 holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // Maintain checkbox state here, which you need to check inside view.setOnClickListener..
            }
        });

如果上面没有帮助,也发布'行'布局。

答案 2 :(得分:0)

// Define size as per your list.
     boolean[] itemChecked = new boolean[YourList.size()];


     holder.ck1.setChecked(false);

    // check its already checked..

      if (itemChecked[position])
       holder.ck1.setChecked(true);
      else
       holder.ck1.setChecked(false);

    holder.ck1.setOnClickListener(new OnClickListener() {
       @Override
       public void onClick(View v) {
        // TODO Auto-generated method stub
        if (holder.ck1.isChecked())
         itemChecked[position] = true;
        else
         itemChecked[position] = false;
       }
      });

答案 3 :(得分:0)

试试这个

private ArrayList<StudentData> selectedUserArrayList = new ArrayList<>(); // Declare globally
public static int i; // Declare globally

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View view = convertView;
    final ViewHolder holder;

    if (view == null){
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        view = inflater.inflate(row, parent, false);

        holder = new ViewHolder();

        holder.studentName = (TextView) view.findViewById(R.id.studentName);
        holder.id = (TextView) view.findViewById(R.id.studentID);
        holder.checkBox = (CheckBox) view.findViewById(R.id.checkBox);


        view.setTag(holder);

    } else {
        holder = (ViewHolder) view.getTag();
    }

    if((data == null) || ((position+1) > data.size()))
        return view;

    studentData = data.get(position);


        viewHolder.checkbox.setOnCheckedChangeListener(null);
        viewHolder.checkbox.setChecked(selectedUserArrayList.contains(user));
        viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {
                    i = user.getUserId();
                    selectedUserArrayList.add(user);
                } else {
                    if (i == user.getUserId()) {
                        i = 0;
                    }
                    selectedUserArrayList.remove(user);
                }
            }
        });
    if ((holder.studentName != null) && null != studentData.getName()
            && studentData.getName().trim().length() > 0 )
        holder.studentName.setText(Html.fromHtml(studentData.getName()));

    if ((holder.id != null) && null != studentData.getAcademicId()
            && studentData.getAcademicId().trim().length() > 0 )
        holder.id.setText(Html.fromHtml(studentData.getAcademicId()));


    return view;
}