为
android
的系统控件添加属性
在
android
的开发过程如果控件需要使用自定义属性有两种方法:
一:继承原有控件,增加自定义的属性。
这个方法可以参考以下文章:
二:修改控件的源码,对控件增加新的属性。本文主要讨论这种情况。
比如对
TextView
控件添加
android:myattr
属性,这样就可以在
XML
直接用以下代码定义
<TextView
android:myattr= "true"
android:text= "@string/hello_world" />
第一步:在
framework
中新增属性,
修改
frameworks/base/core/res/res/values/attrs.xml
加入
<attr name=”myattr” format=”boolean”>
第二步:为这个属性增加 id
修改
frameworks/base/core/res/res/values/public.xml
加入
<public type=”attr” name=”myattr” id=”0x010103cd”/>
注意这个 id 不要和已经有的 id 重复。 Id 中各个位的含义请看以下网页:
这里引用该文章的图:
Android
在编译过程中就是在生成的
out/target/common/R/android/R.java
中加入
public static final int myattr=0x010103cd;
public static final int TextView_myattr = 76;
第三步:就可以在
TextView
类中使用
TextView_myattr
frameworks/base/core/java/android/widget/TextView.java
private boolean myattr = false;
public TextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
…
a = theme.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.TextView, defStyle, 0);
int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = a.getIndex(i);
switch (attr) {
…
case com.android.internal.R.styleable.TextView_uureverse:
myattr = a.getBoolean(attr, myattr);
break;
…
剩下的就是在这个类中添加
myattr
的具体实现方法。