返回

用代码让TextView样式飞起来!支持Padding的StrokeTextView

Android

在本文的第一部分中,我们介绍了如何使用自定义属性创建简单的StrokeTextView。现在,我们将继续完善这个控件,使其支持各种Padding。

首先,我们需要在布局文件中添加一个新的属性,该属性用于设置TextView的Padding。

<declare-styleable name="StrokeTextView">
    <attr name="android:padding" format="dimension"/>
</declare-styleable>

然后,我们需要在StrokeTextView类中添加一个新的成员变量来存储Padding。

private int padding;

接下来,我们需要在StrokeTextView的构造函数中初始化padding成员变量。

public StrokeTextView(Context context, AttributeSet attrs) {
    super(context, attrs);

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.StrokeTextView);
    padding = a.getDimensionPixelSize(R.styleable.StrokeTextView_android_padding, 0);
    a.recycle();
}

最后,我们需要在StrokeTextView的onDraw()方法中应用padding。

@Override
protected void onDraw(Canvas canvas) {
    // Draw the stroke
    RectF rect = new RectF(0, 0, getWidth(), getHeight());
    rect.inset(padding, padding);
    paint.setStrokeWidth(strokeWidth);
    canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint);

    // Draw the text
    super.onDraw(canvas);
}

现在,我们已经创建了一个自定义的TextView,它支持Padding。我们可以通过在布局文件中设置padding属性来控制TextView的Padding。

<com.example.stroketextview.StrokeTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello, world!"
    android:padding="10dp"
    android:textColor="#ffffff"
    android:strokeWidth="2dp"
    android:strokeColor="#000000"
    android:cornerRadius="5dp" />

这样,就可以轻松创建自定义UI了。

希望本教程对您有所帮助!如果您有任何问题,请随时留言。

结语

感谢您阅读本教程。我希望您已经学会了如何创建自定义的TextView,它支持Padding。如果您有任何问题,请随时留言。