【安卓】自定義支持圓角的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"/>

這樣顯然就方便很多了。

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