带边框的TextView

公司最开始设计的草图里面,有个省份选择的Gridview,最初就是想通过Adapter里面getView返回带边框的View

                                                 

后来通过GridView设置水平垂直间距解决,让背景为黑色,然后设置间距,就露出下面的背景,看起来跟边框效果一样

但是后面的各种表格的设计让我觉得 我还是的去做一个带边框的TextView


                            
 

 网上查了下,写的人也蛮多的,我就整理个demo出来吧,反正是当做自己的积累

思路很简单,在TextView的onDraw里面drawRec就可以了~

我在这个基础上扩充了下,设置边框颜色以及粗细,顺便学习了下自定义控件的属性设置

上效果图吧,中间是一个较粗的绿色的边框,下面是一个红色较细的边框


                             
 

@Override
protected void onDraw(Canvas canvas) {
	super.onDraw(canvas);
	drawStroke(canvas);
}

是的,只是在onDraw里面花一个矩形就可以~

private void drawStroke(Canvas canvas) {
	Rect rect = new Rect();
	Paint paint = new Paint();
	paint.setStyle(Paint.Style.STROKE);
	paint.setColor(mStrokeColor);//设置画笔颜色
	paint.setStrokeWidth(mStrokeWidth);//设置画笔粗细
	getLocalVisibleRect(rect);
	canvas.drawRect(rect, paint);
}

 为了显摆一下在里面加入了边框颜色以及粗细的控制,当然你也完全可以不设置,有默认的

private int mStrokeColor;
private float mStrokeWidth;

public TextViewStroke(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.stroke);
    mStrokeColor = typedArray.getInt(R.styleable.stroke_strokeColor,Color.BLACK);
    mStrokeWidth = typedArray.getDimension(R.styleable.stroke_strokeWidth, 2);
    typedArray.recycle();
}

好吧,我也是刚学自定义,那个R.styleable.stroke就是我们定义的可以在xml布局里面设置的属性就像这样

<com.zig.textviewstroke.TextViewStroke
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:gravity="center"
        android:layout_centerInParent="true"
        android:text="zig 出品"
        stroke:strokeColor = "#3b7d19"
        stroke:strokeWidth = "5dp"/>

最后那两行的自定义属性就是在R.styleable.stroke这里面自己设置的,你可以设置任何你想要的属性,然后在你控件那个类里面进行取得相应的值就可以

R.styleable.stroke这个值对应的文件在values的attrs.xml里面

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="stroke">
        <attr name="strokeColor"  format="color"/>
        <attr name="strokeWidth"  format="dimension"/>
    </declare-styleable>
    
</resources>

注意,在布局里面使用自定义组件时候,如果用自己的属性,要控件所在的布局文件的xml中写出你的namespace也就是stroke:strokeColor的前面那个stroke

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
    xmlns:stroke="http://schemas.android.com/apk/res/com.zig.textviewstroke"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

当你实际用的时候把最后面那个包名改成你自己控件对应位置的包名就可以

貌似说清楚了... #83 

好吧就这样,工程在附件中,自己捉摸下,有好建议,欢迎联系我

猜你喜欢

转载自zigtang.iteye.com/blog/1770201
今日推荐