zoukankan      html  css  js  c++  java
  • 练习,自定义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”.

  • 相关阅读:
    学了这些,你就算入门DIV+CSS了(转)
    【转】Web service是什么?
    [转]MongoDB插入和查询操作
    【转】安装m2e最佳方案
    XDS框架基本事务及其Soap消息实例
    数据表改变之后数据的迁移
    HL7 PID (Patient Identification) Segment(HL7规定的PID字段)
    海量数据库的设计
    【转】基于Axis2开发WebService
    【转】JAVA 调用Web Service的方法
  • 原文地址:https://www.cnblogs.com/caoRM/p/4681451.html
Copyright © 2011-2022 走看看