练习,自定义TextView(1.1)

重新自定义TextView是非常有趣的事情,跟着Android4高级编程,通过自定义TextView,来敲一下代码:

这个是那么的简单,自定义TextView,新建CustomTextView继承TextView

public class CustomTextView extends TextView {
	private Paint marginPaint;
	private Paint linePaint;
	private int paperColor;
	private float margin;
	public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}


	public CustomTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public CustomTextView(Context context) {
		super(context);
		init();
	}

	private void init() {
		//获得对资源表的引用
		Resources myResources=getResources();
		//创建将在onDraw方法中使用的画刷
		marginPaint=new Paint(Paint.ANTI_ALIAS_FLAG);
		marginPaint.setColor(myResources.getColor(R.color.noted_margin));
		linePaint=new Paint(Paint.ANTI_ALIAS_FLAG);
		linePaint.setColor(myResources.getColor(R.color.noted_lines));
		//获得页面背景色和边缘宽度
		paperColor=myResources.getColor(R.color.noted_paper);
		margin=myResources.getDimension(R.dimen.noted_margin);
	}


	@Override
	protected void onDraw(Canvas canvas) {
		//绘制页面的颜色
		canvas.drawColor(paperColor);
		
		//绘制边缘
		canvas.drawLine(0, getMeasuredHeight(),getMeasuredWidth(), getMeasuredHeight(), linePaint);
		
		//draw margin
		canvas.drawLine(margin, 0, margin, getMeasuredHeight(), marginPaint);
		
		//移动文本,让它跨过边缘
		canvas.save();
		canvas.translate(margin, 0);
		//使用TextView渲染文本
		super.onDraw(canvas);
		canvas.restore();
	}
	
	
}

xml:
    <com.example.customtextviewbychen.CustomTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

  

 

  it is very important to learn the knowledge about “onDraw”.

posted @ 2015-07-27 22:31  草人木  阅读(214)  评论(0编辑  收藏  举报