为 android的系统控件添加属性

来源:互联网 发布:网络舆情试题 编辑:程序博客网 时间:2024/05/17 09:17
 android的系统控件添加属性

android 的开发过程如果控件需要使用自定义属性有两种方法:
一:继承原有控件,增加自定义的属性。
       这个方法可以参考以下文章:
 Android 中自定义控件和属性 (attr.xml,declare-styleable,TypedArray) 的方法和使用 
http://blog.csdn.net/jincf2011/article/details/6344678

二:修改控件的源码,对控件增加新的属性。本文主要讨论这种情况。
        比如对 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 Resource处理流程分析 -- R.java文件中资源 ID的含义 
http://blog.csdn.net/hao1056531028/article/details/8756647
这里引用该文章的图:

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 的具体实现方法。