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”.

  • 相关阅读:
    PHP无限极分类
    MySQL批量插入测试数据
    MySQL常见面试知识点汇总
    小程序交易组件-自定义交易组件相关知识
    Matplotlib
    sklearn之计算回归模型的四大评价指标(explained_variance_score、mean_absolute_error、mean_squared_error、r2_score)
    pandas.core.frame.DataFrame 切片技巧
    Pyspider all 出现的坑
    mysql 问题
    爬虫遇到HTTP Error 403的问题
  • 原文地址:https://www.cnblogs.com/caoRM/p/4681451.html
Copyright © 2011-2022 走看看