本文将简单介绍自定义控件、其中将会详细介绍关于
自定义在layout中xml布局的属性如下:
<com.edu.testview.MyView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/s"
app:x="100"
app:y="120"
></com.edu.testview.MyView>
一、在res/values中定义文件attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="declareXY">
<attr name="x" format="integer"></attr>
<attr name="y" format="integer" />
</declare-styleable>
</resources>
关于如何定义该xml 详见参考链接:
二、自定义View的代码
package com.edu.testview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class MyView extends View{
private Paint mPaint=new Paint();
int x=1,y=1;
public MyView(Context context, AttributeSet attrs){
super(context,attrs);
//MyView(context,attrs,1)
getSet(context, attrs);
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// MyView(context,attrs);
// TODO Auto-generated constructor stub
getSet(context, attrs);
}
/**
*
* @Description:
*@date 2012-5-30 下午4:12:20
*/
private void getSet(Context context, AttributeSet attrs){
TypedArray aTypedArray=context.obtainStyledAttributes(attrs, R.styleable.declareXY);
int x1=aTypedArray.getInt(R.styleable.declareXY_x,30);
int y2=aTypedArray.getInt(R.styleable.declareXY_y, 30);
x=x1;
y=y2;
//
int sum = attrs.getAttributeCount();
System.out.println("sum>>>>>>>>"+sum);
String str = "";
for (int i = 0; i < sum; i++) {
String name = attrs.getAttributeName(i);
String value = attrs.getAttributeValue(i);
str += "attr_name :" + name + ": " + value + "\n";
}
Log.i("attribute", str);
System.out.println(str+">>>>>>>>>>");
//System.out.println(count);
//System.out.println(attrs.getAttributeCount());
aTypedArray.recycle();
}
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
mPaint.setColor(Color.BLUE);
canvas.drawRect(new Rect(x, y, 200, 200), mPaint);
}
}
三、在layout布局中调用
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.edu.testview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<com.edu.testview.MyView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/s"
app:x="100"
app:y="120"
></com.edu.testview.MyView>
</LinearLayout>
请注意 xmlns:app="http://schemas.android.com/apk/res/com.edu.testview"这句话。
属性的前缀名 包名
源码下载地址http://download.csdn.net/detail/qq282133/4340233
参考: