Outline Provider not working anymore

4.6k Views Asked by At

I'm trying to set an outline to a view (a Floating Action Button). The point is in that it used to work for a while, so no problem in code nor error and it was showing the shadow perfectly. Then it stopped showing a shadow from nowhere. I think I've checked everything has to do with this and cannot find the problem.

So this is my code I've been working on:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        ImageButton fab = (ImageButton) findViewById(R.id.fab);

        ViewOutlineProvider outlineProvider = new ViewOutlineProvider() {
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void getOutline(View view, Outline outline) {
                int fabSize = view.getHeight();
                //int fabSize = getResources().getDimensionPixelSize(R.dimen.fab_big);
                outline.setOval(0, 0, fabSize, fabSize);
            }
        };
        fab.setOutlineProvider(outlineProvider);
}

And my fab is a simple ImageButton with a ripple as background and an image src (a plus sign) inside 56*56dp.

Any suggestion?

EDIT: after few days I would say that the outline provider only works for Button and not for ImageButton ... further test coming in a few hours.

2

There are 2 best solutions below

0
On

You can try like this without margin was set:

setClipToOutline(true);
setOutlineProvider(new ViewOutlineProvider() {
    @Override
    public void getOutline(View view, Outline outline) {
        outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), cornerSize);
    }
});

Otherwise:

setOutlineProvider(new ViewOutlineProvider() {
  @Override
  public void getOutline(View view, Outline outline) {
    Rect rect = new Rect();
    view.getGlobalVisibleRect(rect);
    ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
    int leftMargin = layoutParams.leftMargin;
    int topMargin = layoutParams.topMargin;
    rect.set(leftMargin, topMargin, rect.right - rect.left - leftMargin, rect.bottom - rect.top - topMargin);
    outline.setOval(rect);
    view.setClipToOutline(true);
  }
});

and add this View into a ViewGroup as its parent.

0
On

In your getOutline method, you should set clip to outline true:

public void getOutline(View view, Outline outline) {
    int fabSize = view.getHeight();
    outline.setOval(0, 0, fabSize, fabSize);
    view.setClipToOutline(true);
}