简体   繁体   中英

Only click Checkbox in clickable Relative Layout

I'm trying to design a layout with a checkbox inside of a relative layout. The relative layout is clickable and works as it is supposed to, but when the checkbox is click, it runs the checkbox code, and the relative view code.

Is there anyway to ignore the relative layout's OnClickListener while running the checkbox?

RelativeLayout holder = new RelativeLayout(context);
contactHolder.setId(View.generateViewId());

TextView name = new TextView(context);
final CheckBox checkBox = new CheckBox(context);

checkBox.setId(View.generateViewId());

name.setText(contact.getName());
name.setId(View.generateViewId());

holder.addView(name);
holder.addView(checkBox);

checkBox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!checkBox.isChecked()) {
                checkBox.setChecked(true);
            }
            else if (checkBox.isChecked()){
                checkBox.setChecked(false);
            }
        }
    });

holder.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (!checkBox.isChecked()) {
            checkBox.setChecked(true);
        }
        else if (checkBox.isChecked()){
            checkBox.setChecked(false);
        }
    }
});
userView.addView(holder);
}

在Relativelayout中使用它

android:clickable="true"

Remove the listener from the check box. Then change the logic in RelativeLayout's listener to act based on the state of the check box.

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