Tears_fg

导航

自定义圆角背景的textview,抛弃shape

自定义一个圆角背景的TextView,解放双手,不用再写shape了。

1.values目录新建attrs.xml。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="test">
        <attr name="radius" format="integer" />
        <attr name="stokeWidth" format="float" />
        <attr name="stokeColor" format="reference|color"/>
        <attr name="solidColor" format="reference|color"/>
    </declare-styleable>
</resources>

2.新建类继承TextView。

public class CustomRoundTextView extends AppCompatTextView {
    private  int solidColor;
    private  int stokeColor;
    private float stokeWidth;
    private  int cornerRadius;
    private Paint mPaint;
    public CustomRoundTextView(Context context) {
        super(context);
        init();
    }



    public CustomRoundTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.test);
        cornerRadius = typedArray.getInteger(R.styleable.test_radius, 20);
        stokeWidth = typedArray.getFloat(R.styleable.test_stokeWidth, 0.5f);
        solidColor = typedArray.getColor(R.styleable.test_solidColor, getResources().getColor(android.R.color.white,null));
        stokeColor = typedArray.getColor(R.styleable.test_stokeColor,solidColor );

        init();
    }

    public CustomRoundTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        GradientDrawable gd = new GradientDrawable();
        gd.setCornerRadius(dip2px(cornerRadius));
        gd.setStroke(dip2px(stokeWidth), stokeColor);
        gd.setColor(solidColor);
        setBackgroundDrawable(gd);
    }




    public int dip2px(float dpValue) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

}

 

3.xml文件中使用。

 <com.example.myapplication.CustomRoundTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"
        android:textSize="16sp"
        android:text="这是一个test"
        android:textColor="#000000"
        app:radius="5"
        app:stokeWidth="0.5"
        app:stokeColor="#000000"
        app:solidColor="#ff00000"
        />

4.圆形自定义也可以拓展实现。

 效果实现如下:

自定义view相关博客:

1.Android自定义View全解

2.自定义控件

3.Android View的绘制流程

 

posted on 2020-04-21 19:18  Tears_fg  阅读(611)  评论(0编辑  收藏  举报