Android 自定义view

自定义view,实现TextView效果,可以设置textColor和textSize


1.MyView.java

package com.example.myview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

public class MyView extends View{
	
	private Paint paint;
	public MyView(Context context) {
		super(context);
	}
	public MyView(Context context, AttributeSet attrs) {
		super(context, attrs);
			//Paint: 画笔 用来画文字或者图形,可以设置颜色等
			paint = new Paint();   
			//TypedArray:用来存储自定义的属性
			// R.styleable.MyView:自定义属性的xml文件,一般放在attrs.xml中
	        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyView);   
	        int textColor = array.getColor(R.styleable.MyView_textColor, 0XFF00FF00); //提供默认值 
	        float textSize = array.getDimension(R.styleable.MyView_textSize, 12);   
	        paint.setColor(textColor);   
	        paint.setTextSize(textSize);   
	        array.recycle(); //一定要调用
	}
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		canvas.drawText("Hello World", 10, 100, paint);//显示文字,距离左边,距离上边,画笔
	}

}
2.activity_main.xml

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:myview="http://schemas.android.com/apk/res/com.example.myview"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
	<com.example.myview.MyView 
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	   	myview:textSize = "30sp"
	   	myview:textColor = "#666666"
	    />
</RelativeLayout>
3.attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyView">  
        <attr name="textColor" format="color"/>  
        <attr name="textSize" format="dimension"/>  
    </declare-styleable>  
</resources>

<a target=_blank href="http://download.csdn.net/detail/bei741178678/8425129">源码下载 </a>




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值