练习,自定义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”.

转载于:https://www.cnblogs.com/caoRM/p/4681451.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值