效果图
实现一:shape方案
使用shape实现圆角
第一步:引入shape文件test
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/white" />
<corners android:radius="20dp" />
<stroke
android:width="1dp"
android:color="@android:color/darker_gray" />
</shape>
第二步:在布局文件中引入shape
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="50dp"
android:background="@drawable/test"
>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@android:color/holo_red_dark"
android:layout_marginTop="5dp"
/>
</LinearLayout>
</RelativeLayout>
效果如下
缺点:背景中的内容会覆盖背景。
实现二:使用裁剪实现
使用 canvas.clipPath(path)
第一步:引入自定义布局
package com.example.myapplication;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import androidx.annotation.Nullable;
public class MyLinearLayout extends LinearLayout {
public MyLinearLayout(Context context) {
super(context);
}
public MyLinearLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public MyLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void dispatchDraw(Canvas canvas) {
// 定义区域
RectF rectF = new RectF(0, 0, getWidth(), getHeight());
// 定义裁剪的弧度
float mRadius = getResources().getDimension(R.dimen.dp_20);
// 定义裁剪的路径
Path path = new Path();
path.addRoundRect(rectF, mRadius, mRadius, Path.Direction.CW);
// 进行裁剪
canvas.clipPath(path);
super.dispatchDraw(canvas);
}
}
第二步:在布局文件中引入自定义布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.myapplication.MyLinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="50dp"
android:background="@drawable/test"
>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@android:color/holo_red_dark"
android:layout_marginTop="5dp"
/>
</com.example.myapplication.MyLinearLayout>
</RelativeLayout>
效果图如下