码迷,mamicode.com
首页 > 其他好文 > 详细

练习,自定义TextView(1.1)

时间:2015-07-28 00:35:24      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:

重新自定义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”.

练习,自定义TextView(1.1)

标签:

原文地址:http://www.cnblogs.com/caoRM/p/4681451.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!