自定义view流程:
- 自定义view继承View;
- 自定义View属性;
- 重写3个构造方法(后面解释3个);
- 重写onDraw方法;
- 在values文件夹下建attrs.xml文件
- 完成!
下面以一个demo实现:
自定义MyView继承View
package com.hai.test;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View {
/**
* 框度
*/
private int mCircleWidth;
/**
* 第二圈的颜色
*/
private int mSecondColor;
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray ta = context.getTheme().obtainStyledAttributes(attrs,
R.styleable.MyView, defStyleAttr, 0);
int num = ta.getIndexCount();
for (int i = 0; i < num; i++) {
int id = ta.getIndex(i);
switch (id) {
case R.styleable.MyView_circleWidth:
break;
case R.styleable.MyView_secondColor:
break;
}
}
}
public MyView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyView(Context context) {
this(context, null);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
}
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="secondColor" format="color" />
<attr name="circleWidth" format="dimension" />
<declare-styleable name="MyView">
<attr name="secondColor" />
<attr name="circleWidth" />
</declare-styleable>
</resources>
在布局文件中引用自定义MyView,给自定义属性赋值时eclipse会自动加上命名空间如下:xmlns:app="http://schemas.android.com/apk/res/com.hai.test"
<?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.hai.test"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.hai.test.MyView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:secondColor="#0f0"
app:circleWidth="32" />
</LinearLayout>
附上一张快捷键显示自定义属性的图
注意几个问题:
如在xml中引用自定义View,按快捷键不能显示自定义属性时,解决方法如下:
1,检查自定义View的属性名称和attrs.xml中的属性名称 及(declare-styleable name="MyView")
2,clean下项目
3,重启下eclipse
4,在布局文件中擦掉旧的,重新引入自定义View,
通过以上几部就可以解决 android快捷键不能显示自定义属性 的问题了