您的位置:首页 > 移动开发 > Android开发

Android自定义属性的使用示例

2013-09-02 16:00 405 查看
MainActivity如下:

package cc.testattrs;

import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}
}


ViewSubclass如下:

package cc.testattrs;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.View;
/**
 * Demo描述:
 * Android自定义属性的使用
 * 
 * 注意事项:
 * 1 在main.xml中声明命名空间
 *   xmlns:testattr="http://schemas.android.com/apk/res/cc.testattrs"
 *   其中http://schemas.android.com/apk/res/为固定写法,其后追加包名
 *   testattr为我们给自定义属性的别名引用
 * 2 getDimension(R.styleable.TestAttr_testTextSize, 20);
 *   第二个参数意思是:假如在xml文件中没有为改属性设值则采用此值.
 *   其余getXX()方法均类似
 * 3 注意getColor()方法中第二个参数的取值,是一个颜色值,在这里很容易错误
 *
 */
public class ViewSubclass extends View {
    private Paint mPaint;
    private float textSize;
    private int textColor ;
	public ViewSubclass(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public ViewSubclass(Context context, AttributeSet attrs) {
		super(context, attrs);
		mPaint = new Paint();
		TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.TestAttr);
		textSize = typedArray.getDimension(R.styleable.TestAttr_testTextSize, 20);
		textColor = typedArray.getColor(R.styleable.TestAttr_testColor, Color.BLACK);
		System.out.println("textSize="+textSize+",textColor="+textColor);
		mPaint.setTextSize(textSize);
		mPaint.setColor(textColor);
		//切记recycle()
		typedArray.recycle();
	}

	public ViewSubclass(Context context) {
		super(context);
	}
	
    @Override
    protected void onDraw(Canvas canvas) {
    	super.onDraw(canvas);
    	mPaint.setStyle(Style.FILL);  
    	canvas.drawText("9527", 10, 20, mPaint);
    }
	
}



main.xml如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:testattr="http://schemas.android.com/apk/res/cc.testattrs"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
   >

    <cc.testattrs.ViewSubclass
        android:layout_width="200dip"
        android:layout_height="200dip"
        android:layout_centerInParent="true" 
        testattr:testTextSize="10dip"
        testattr:testColor="#ff0000"
    />

</RelativeLayout>



attrs.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
      <declare-styleable name="TestAttr">
        <attr name="testTextSize" format="dimension"/>
        <attr name="testColor" format="color"/>
    </declare-styleable>
</resources>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: