细致的攻略如下。
1. 准备工作
首先,我们需要在Android Studio中创建一个新项目。然后,在项目中创建一个名为“RoundButton”的java文件,并扩展Button类。接着,我们需要重写onDraw方法,在其中实现自定义圆角按钮的效果。最后,在布局文件中使用自定义的Button组件。
2. 实现圆角按钮效果
以下是实现自定义圆角按钮效果所需的代码:
public class RoundButton extends Button {
private Paint backgroundPaint;
private Paint strokePaint;
private RectF rectF;
public RoundButton(Context context) {
this(context, null);
}
public RoundButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
backgroundPaint = new Paint();
backgroundPaint.setAntiAlias(true);
backgroundPaint.setStyle(Paint.Style.FILL);
strokePaint = new Paint();
strokePaint.setAntiAlias(true);
strokePaint.setStyle(Paint.Style.STROKE);
strokePaint.setStrokeWidth(2);
rectF = new RectF();
}
@Override
protected void onDraw(Canvas canvas) {
backgroundPaint.setColor(Color.BLUE);
strokePaint.setColor(Color.BLACK);
rectF.set(0, 0, getWidth(), getHeight());
canvas.drawRoundRect(rectF, 20, 20, backgroundPaint);
canvas.drawRoundRect(rectF, 20, 20, strokePaint);
super.onDraw(canvas);
}
}
在onDraw方法中,我们定义了两个Paint对象,一个用于绘制背景,一个用于描边。我们创建了一个RectF对象来设置按钮边界。在按钮的背景中使用了画布的drawRoundRect方法来绘制一个带圆角的矩形。在绘制描边时,我们再次绘制圆角矩形,但这次只描边。
3. 在布局文件中使用RoundButton组件
我们已经创建了自定义的RoundButton组件,现在我们需要在布局文件中使用它。我们只需像使用普通按钮一样使用它即可。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.sampleapp.RoundButton
android:layout_width="200dp"
android:layout_height="80dp"
android:text="Custom Button"
android:layout_centerInParent="true"/>
</RelativeLayout>
通过在布局文件中使用自定义的RoundButton组件,我们可以在应用程序中创建带有圆角边框的自定义按钮。
4. 示例说明
示例1:改变圆角的大小
要改变圆角的大小,您可以在onDraw方法中更改第2个和第3个参数。在我们的示例代码中,我们将这两个参数设置为20,最终效果是一个圆角为20的矩形。如果您将这些参数设置为较大的数字,则会获得较大的圆角。
示例2:改变按钮颜色
要更改按钮的颜色,您可以在onDraw方法中更改背景颜色的值。在我们的示例代码中,我们将背景颜色设置为蓝色。如果您更改此值,则按钮的颜色将相应更改。您也可以改变描边的颜色来实现更多的效果。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:android 自定义圆角button效果的实例代码(自定义view Demo) - Python技术站