【安卓】自定义支持圆角的TextView

给textview添加圆角

如果想给一个普通的textview添加圆角、边框等,一般的做法是写一个drawable文件,通过android:background="@drawable/xxxx"设置为textview的背景。麻烦是不麻烦,可是如果项目里出现了很多需要圆角或者边框的需求时,drawable文件会变得很多很乱,维护起来也十分不方便。

如果直接可以通过属性设置radius border borderWidth等属性值,就会方便很多。github上有一个 SuperTextView ,可以实现。但是功能太多太杂了。搜了搜网上的写法,基本都是重新定义view,重写onDraw onMeasure ,可是这些功能textview都有,没必要,况且重写之后,textview的很多功能就没了。

这里的思路是,通过继承TextView来自定义Textview,利用代码来控制drawable文件。代码创建drawable文件的方式如下:

自定义view的方式有三种:组合、继承、完全自定义

GradientDrawable gd = new GradientDrawable();//创建drawable
gd.setColor(rtvBgColor);
gd.setCornerRadius(rtvRadius);

所以方法就是,自定义属性,通过属性值创建drawable文件控制圆角、边框等。如果不设置自定义属性,和一个普通TextView没有任何差别!

代码

/**
 * 支持圆角的TextView
 * Created by stephen on 2017/12/18.
 */
public class RoundTextView extends android.support.v7.widget.AppCompatTextView {

    public RoundTextView(Context context) {
        this(context, null);
    }

    public RoundTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.RoundTextView, defStyleAttr, 0);

        if (attributes != null) {

            int rtvBorderWidth = attributes.getDimensionPixelSize(R.styleable.RoundTextView_rtvBorderWidth, 0);
            int rtvBorderColor = attributes.getColor(R.styleable.RoundTextView_rtvBorderColor, Color.BLACK);
            float rtvRadius = attributes.getDimension(R.styleable.RoundTextView_rtvRadius, 0);
            int rtvBgColor = attributes.getColor(R.styleable.RoundTextView_rtvBgColor, Color.WHITE);
            attributes.recycle();

            GradientDrawable gd = new GradientDrawable();//创建drawable
            gd.setColor(rtvBgColor);
            gd.setCornerRadius(rtvRadius);
            if (rtvBorderWidth > 0) {
                gd.setStroke(rtvBorderWidth, rtvBorderColor);
            }

            this.setBackground(gd);
        }
    }

    public void setBackgroungColor(@ColorInt int color) {
        GradientDrawable myGrad = (GradientDrawable) getBackground();
        myGrad.setColor(color);
    }
}

attr中添加属性

<!--支持圆角的TextView-->
<declare-styleable name="RoundTextView">
    <attr name="rtvBgColor" format="color"/>
    <attr name="rtvBorderWidth" format="dimension"/>
    <attr name="rtvBorderColor" format="dimension"/>
    <attr name="rtvRadius" format="dimension"/>
</declare-styleable>

代码使用

 <io.github.imwyy.RoundTextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="浏览"
                android:textColor="@color/text_black_select_color"
                android:textSize="@dimen/sp_14"
                app:rtvRadius="6dp"
                app:rtvBgColor="@color/colorSearchArea"/>

这样显然就方便很多了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章