转载出处:https://www.cnblogs.com/setsailwu/p/3852261.html
转载里的文章挺好,但是按照里面的步骤实际操作时,有些步骤对于新手来说会不懂为什么这么做。所以记录一下,我实际有效的操作步骤:
Android 系统开发时,比如想给系统的EditText新增一个xml属性,新增后,其他app都可以调用这个属性。
比如新增一个,点击返回键时,不删除字符串,删除字符串的功能由其他按键控制,返回键只做返回作用。
<EditText
android:resetBackKey= "true"
android:inputType= "text" />
第一步:
原文:修改 frameworks/base/core/res/res/values/attrs.xml
加入
<attr name=”resetBackKey” format=”boolean”>
疑惑点:转载原文是上面这样写的,我在attrs.xml底部新增一个之后,发现调用不了,不生效。
解决方式:查看原文后面的代码,以及参考系统的操作,终于知道,这个<attr属性,要放到这里面:
<declare-styleable name="TextView">
.........
<attr name=”resetBackKey” format=”boolean”>
</declare-styleable>
我要增加的虽然是EditText的属性,但是attrs.xml里没有找到<declare-styleable name="EditText"> ,由于EditText是TextView的子类,所以可以放到TextView里面。
这里是很关键的一步,因为只有放到TextView里面,然后make update-api,就会在out/target/common/R/android/R.java
下生成一条的属性:
public static final int TextView_resetBackKey = 76;
这个属性后面会在EditText.java中用到
第二步:
原文:
修改 frameworks/base/core/res/res/values/public.xml
加入
<public type=”attr” name=”resetBackKey” id=”0x010103cd”/>
这里改的时候,我并没有增加id,直接写<public type=”attr” name=”resetBackKey” />,因为我看其他人增加的attr都没有id,也就不搞那么多花里胡哨的了。
第三步:去frameworks/base/core/java/android/widget/EditText.java中读取属性,并使用。
private boolean resetBackKey = false;//最终为的是得到这个值,进而进行其他操作
public EditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle)
//系统源码中其他的属性也有例子,都是下面这样做。
final Resources.Theme theme = context.getTheme();
TypedArray a = theme.obtainStyledAttributes(attrs,
com.android.internal.R.styleable.TextView, defStyleAttr, defStyleRes);
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_resetBackKey://注意这个TextView_resetBackKey怎么来的
resetBackKey = a.getBoolean(attr, resetBackKey);//根据xml得到一个值
break;
}
}
a.recycle();
}
这个步骤重要的点就是把第一步编译得来的属性TextView_resetBackKey,作为读取的值。
第四步 :编译一遍系统源码,之后就可以再其他app中使用这条公共属性了。