Question

I have 5 linearlayouts each which contain a radiobutton and an ImageView and some padding. I'd like the radiobutton to be clicked if the user clicks on any part of the linearlayout in which the radiobutton is contained. In order to get the onpressed status of the radiobutton I thought dispatching a touch event from an ontouchlistener was the best way to do this.

My problem is how do I best implement this?

This was one way I tried manually setting the pressed state:

@Override
public boolean onTouch(View v, MotionEvent arg1) {
            //gets the index of which LinearLayout was touched
    int rb = lArray.indexOf(v);
            // uses this to identify the LinearLayout and RadioButton to control
    LinearLayout l = lArray.get(rb);
    RadioButton r = rbArray.get(rb);

    switch (arg1.getAction()) {
    case MotionEvent.ACTION_DOWN:
        Sy = arg1.getY();
        if (rb != -1) {
            r.setPressed(true);
        }
        break;
    case MotionEvent.ACTION_MOVE:
        My = arg1.getY();
        if (rb != -1 && Math.abs(Sy - My) > l.getHeight() / 2) {
            r.setPressed(false);
        }
        break;
    case MotionEvent.ACTION_UP:
        My = Sy = 0;
        if (rb != -1) {
            if (r.isPressed() && r.isEnabled()) {
                r.performClick();
            }
        }
        for (RadioButton b : rbArray) {
            b.setPressed(false);
        }
        break;
    }
    return true;
}
}

This works fairly well but causes occasional hiccups with the onPressed state permanently remaining when a user sometimes drags their finger off the layout.

Another attempt was this:

@Override
public boolean onTouch(View v, MotionEvent event) {

    int rb = lArray.indexOf(v);
    RadioButton r = rbArray.get(rb);

        r.dispatchTouchEvent(event);

    return true;
            }

However this only calls onclick if it really is just clicked but inactivates if the user drags their finger across the layout.

Is there a way I could do this?

Was it helpful?

Solution 2

Used if linearlayout is on pressed then set radiobutton to on pressed in an on touch listener and also added an onclick listener. Both together worked perfectly!

OTHER TIPS

You are trying to select (or unselect) the radio button if they click on the linear layout? Why not just set a click listener on the layout and then programmatically select the radio button?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top