Search code examples
androidviewcustom-componentviewgroup

Select only one children in custom layout per time


I'm stuck with this: I have a ViewGroup that hosts few Views. All Views has layout parameters: match_parent/match_parent. Views can be placed one over another like on the picture.

On touch event View should be selected (if tap happend over its filled rectangle) and only one View can be selected per time.

What is the best way to implement this?

enter image description here

UPD:

code in View:

@Override
public boolean onTouchEvent(MotionEvent event) {
    float eventX = event.getX();
    float eventY = event.getY();
    // if it's over filled area
    if (mBounds.contains((int)eventX, (int)eventY)) {
        // set current view selected or perform other stuff
        // also at this moment we need to unselect all siblings
        mGestureDetector.onTouchEvent(event); 
        return true;
    } else {
        setSelected(false);
        return false;
    }
}

Solution

  • Create a field representing the current child View selected in the custom ViewGroup. When you encounter a touch event then check if you have a previous View selected and if it is by any chance the same view. If it isn't then uncheck the previous view and make it point to the current one. I'm guessing that the code posted is for a child view, in this case you could create a callback interface where the parent ViewGroup implements the interface that will be called each time a view gets selected. Below is a small template:

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float eventX = event.getX();
        float eventY = event.getY();
        // if it's over filled area
        if (mBounds.contains((int)eventX, (int)eventY)) {
            mListener.onViewSelected(this);
            // set current view selected or perform other stuff
            // also at this moment we need to unselect all siblings
            mGestureDetector.onTouchEvent(event); 
            return true;
        } else {
            setSelected(false);
            return false;
        }
    }
    

    and in the parent ViewGroup:

    public class NiceViewGroup extends ViewGroup implements OnViewSelected {
    
       private View mCurrentSelectedView = null;
    
       public void onViewselected(View selected) {
            if (mCurrentSelectedView == null || mCurrentSelectedView == selected) {
                 return;
            } else {
                 mCurrentSelectedView.unselectView();
                 mCurrentSelectedView = selected;      
            }    
       }        
    

    Of course you would have to pass as the listener the parent ViewGroup when you create the child views.