Pages

Wednesday 18 January 2017

Android popup menu display causes RecyclerView scroll up

If you using android.support.v7.widget.PopupMenu then you may face this issue. Simple solution is to use android.widget.PopupMenu.

But if you need to show icons in your popupMenu then you have to use android.support.v7.widget.PopupMenu. so you should apply following solution.


You can have your AnchorView override requestRectangleOnScreen() and return false. This will prevent any parent ScrollView or RecyclerView from scrolling.

So, For ex If I have anchor view as ImageView then code should be like following.



public class MenuImageView extends ImageView {
    public MenuImageView(Context context) {
        super(context);
    }

    public MenuImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MenuImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public MenuImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

// THIS IS IMP METHOD (RETURN FALSE). ADD IT SO YOUR RECYCLER VIEW WILL NOT SCROLL WHEN YOU CLICK ON MENU.
    @Override
    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
        return false;
    }
}