Android 设置Layout背景圆角裁剪

比如, 现在有一个FrameLayout, 里面包含了一个RecyclerView, 需要设置外层的圆角为12. 可以有如下2种方式操作:

第一种, 通过代码方式设置outline裁剪
       mFrameLayout.setOutlineProvider(new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setRoundRect(0,
                        0,
                        view.getWidth(),
                        view.getHeight(),
                        ConvertUtils.dp2px(12));
            }
        });
        mFrameLayout.setClipToOutline(true);

第一个方法设置View的轮廓, 第二个方法开始轮廓裁剪. 这样就可以只保留圆角矩形部分了.
效果图如下:


Jan-08-2020 16-40-27.gif

使用到的布局代码如下:
FrameLayoutRecyclerView

    <FrameLayout
        android:id="@+id/frame"
        android:layout_width="200dp"
        android:layout_height="200dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" >

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycler"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>
第二种, 通过shape方式

这种方式更简单,

  1. 直接设置一个带圆角的shape
    <FrameLayout
        android:id="@+id/frame"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="@drawable/shape_round_corner/>
    
<!--    省略了ReyclerView部分代码-->

    </FrameLayout>

其中, drawable的shape部分代码如下:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="12dp" />
</shape>
  1. 开启View的轮廓裁剪
mFrameLayout.setClipToOutline(true);
其他, 用到的RecyclerView的Item代码
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:padding="8dp"/>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容