现在的位置: 首页 > 综合 > 正文

android 用代码分别实现textview的背景和圆角

2018年04月04日 ⁄ 综合 ⁄ 共 2023字 ⁄ 字号 评论关闭

       设置view的圆角和背景一般都是在xml里面通过selector的配置文件来写的。在项目中有个需求,背景颜色是从网络获取的,而且要设置为圆角,想了一下,通过xml的形式貌似实现不了,只能通过代码分别设置,就只能重写Textview。

    来,上代码:

package com.paddy.roundtextviewdemo.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.paddy.roundtextviewdemo.R;

public class RoundTextView extends TextView {

private Context mContext;
private int mBgColor = 0;
private int mCornerSize = 0;

public RoundTextView(Context context, AttributeSet attrs) {
super(context, attrs);
getAttrs(context, attrs);
mContext = context;
}

@Override
    protected void onDraw(Canvas canvas)
    {
   setBackgroundRounded(canvas, this.getMeasuredWidth(), this.getMeasuredHeight(), this);
        super.onDraw(canvas);
    }

    private void getAttrs(Context context, AttributeSet attrs) {
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.round_textview);
        mBgColor = ta.getColor(R.styleable.round_textview_round_tv_color, R.color.blue);
        mCornerSize = (int)ta.getDimension(R.styleable.round_textview_round_tv_corner_size, 8);
        
        ta.recycle();
    }

    public void setBackgroundRounded(Canvas c, int w, int h, View v){
    if(w <= 0 || h <= 0){
    return;
    }
   
        Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
        paint.setAntiAlias(true);
        paint.setColor(mBgColor);
        
        RectF rec = new RectF(0, 0, w, h);
        c.drawRoundRect(rec, mCornerSize, mCornerSize, paint);
    }
}

在调用它的activity里面,需要重新设置一下显示的内容,这样会让view重绘,如下:

public class MainActivity extends Activity {

private RoundTextView mTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTv = (RoundTextView)findViewById(R.id.testTv);
        mTv.setText("good");
    }

}

源码demo链接附上:http://download.csdn.net/detail/paddyy/8266287

注意:这个demo要改一下,换成blog中的代码(ps:不知道怎么删除之前上传的资源,貌似没这个功能)

抱歉!评论已关闭.