简体   繁体   中英

Android onClick checkbox not checked in listview

I am working on Customized ListView using CheckBox . I tried to check single selection CheckBox when we click in Item of ListView . How can I do it?

My XML code

<TextView
    android:id="@+id/addressTXT"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_marginTop="10dp"
    android:text="Price" />

<CheckBox
    android:id="@+id/addressCheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_toRightOf="@+id/addressTXT"
    android:layout_marginRight="40dp"
    android:focusable="false"
    android:focusableInTouchMode="false" />

and Click Item in BaseAdapter .

         itemView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        }
    });

How can I do it?

Ahhhh I faced same issue :) I solved this thing like below.

    itemView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            for (int i = 0; i < parent.getChildCount(); i++) {

                View view = parent.getChildAt(i);
                CheckBox checkBox = (CheckBox) view
                        .findViewById(R.id.CheckBox);
                checkBox.setChecked(false);

            }

            CheckBox checkBox = (CheckBox) v
                    .findViewById(R.id.CheckBox);
            checkBox.setChecked(true);

        }
    });

You could do this:

    itemView.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        CheckBox box = v.findViewById(R.id.addressCheckBox); //get your checkbox
        box.setChecked(!box.isChecked()); //toggle checkbox-state
    }
});

First you have to pun onClickListener for checkBox, not on whole view. and second, in XML for adapter you have to put this for checkBox

android:focusable="true"
android:clickable="true"

if you need separate clickListeners for check box and for listView row you need this parameters in XML for checkBox

android:focusable="false"
android:clickable="true"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM