Android开发中,为了UI的美观展示,经常会设置控件的圆角弧度。与IOS不同的是,Android设置圆角比较麻烦,需要单个设置shape乃至自定义圆角View。本文介绍ViewOutlineProvider的圆角设方式(方便,推荐),并一并将Android其他常用的圆角设置进行介绍。

一 ViewOutlineProvider

ViewOutlineProvider是Android 5.x引入的新特性,它是View类中的方法,用于实现View的阴影和轮廓,用ViewOutlineProvider可以快捷地实现控件的原件(Kotlin实现):

// 设置View圆角radius
fun setRadius(view : View, radius:Float){
view.run {
outlineProvider = object : ViewOutlineProvider() {
override fun getOutline(view: View, outline: Outline) {
// 设置圆角率为
outline.setRoundRect(0, 0, view.width, view.height, radius)
}
}
clipToOutline = true
}
}

二 shape元素

drawable文件夹中新建shape.xml,之后在布局文件中设置背景为shape.xml。

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">

<corners android:radius="6dp"/> <!-- 设置圆角弧度 -->
<solid android:color="#FF95CA"/> <!-- 设置背景颜色 -->
<stroke android:color="#D200D2" android:width="2dp"/> <!-- 设置边框颜色以及宽度 -->

</shape>

三 自定义View

在values文件中的attrs文件(没有自己创建)中添加:

<?xml version="1.0" encoding="utf-8"?>
<resources>

<declare-styleable name="CustomButton">
<!-- 圆角半径 -->
<attr name="radius" format="dimension" />
<!-- 背景颜色 -->
<attr name="normal_color" format="reference|color" />
</declare-styleable>

</resources

自定义Button,继承Button/AppCompatButton (Java实现)

package com.example.myapplication;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.util.AttributeSet;
import android.view.Gravity;

import androidx.appcompat.widget.AppCompatButton;

public class CustomButton extends AppCompatButton {

private float radius; // 圆角半径
private int normalColor; // 按钮正常时的背景颜色
private GradientDrawable gradientDrawable;

public CustomButton(Context context) {
this(context, null, 0);
}

public CustomButton(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

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

initAttris(attrs);
init();
}

private void init() {
setGravity(Gravity.CENTER);
gradientDrawable = new GradientDrawable();
gradientDrawable.setCornerRadius(radius);
gradientDrawable.setColor(normalColor);
// 设置圆角的关键
setBackground(gradientDrawable);
}

/**
* 属行初始化
*
* @param attrs
*/
private void initAttris(AttributeSet attrs) {
if (attrs != null) { // 获取自定义属性
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.CustomButton);
radius = (int) typedArray.getDimension(R.styleable.CustomButton_radius, 10);
normalColor = typedArray.getColor(R.styleable.CustomButton_normal_color, Color.parseColor("#FF0080"));
typedArray.recycle();
}
}
}

使用:

<com.example.myapplication.CustomButton
android:id="@+id/btn_test"
android:layout_width="128dp"
android:layout_height="44dp"
app:radius="18dp"
app:normal_color="#00BB00"
android:textColor="@color/white"
android:text="测试"/>

小结:

除以上三种方式外,还可以采用CardView或者其他三方库。shape方式是安卓最基础的实现方式,自定义控件稍显麻烦(但是实现在xml中),推荐采用第一种方式,写在工具类中,可以一行代码搞定(缺点也很明显,UI逻辑跑到了activity中)。