Android:自定义视图,对象引用来自attrs.xml,始终为null



我正在尝试设置对象之间的关系层次结构。每个对象都有一个与自身类型相同的父对象,即null

我有一个包含以下内容的main.xml

<com.morsetable.MorseKey
    android:id="@+id/bi"
    android:layout_weight="1"
    custom:code=".."
    custom:parentKey="@id/be"
    android:text="@string/i" />

包含以下内容之一的res/values/attrs.xml

<declare-styleable name="MorseKey">
    <attr name="code" format="string"/>
    <attr name="parentKey" format="reference"/>
</declare-styleable>

以及一个包含以下内容的类(这不是我的活动):

public class MorseKey extends Button {
    public MorseKey(Context context, AttributeSet attrs) {
        super(context, attrs);
        initMorseKey(attrs);
    }
    private void initMorseKey(AttributeSet attrs) {
        TypedArray a = getContext().obtainStyledAttributes(attrs,
                          R.styleable.MorseKey);
        final int N = a.getIndexCount();
        for (int i = 0; i < N; i++) {
            int attr = a.getIndex(i);
            switch (attr)
            {
            case R.styleable.MorseKey_code:
                code = a.getString(attr);
                break;
            case R.styleable.MorseKey_parentKey:
                parent = (MorseKey)findViewById(a.getResourceId(attr, -1));
                //parent = (MorseKey)findViewById(R.id.be);
                Log.d("parent, N:", ""+parent+","+N);
                break;
            }
        }
        a.recycle();
    }
    private MorseKey parent;
    private String code;
}

这不起作用。每个MorseKey实例报告N == 2(好)和parent == null(坏)。更重要的是,即使我明确地尝试将parent == null设置为某个任意值(请参阅注释)。我也试过custom:parentKey="@+id/be"(带加号),但也没用。我做错了什么?

如果您的MorseKey类在一个单独的java文件中,我认为这是您的声明"一个类(不是我的活动)"中的情况。那么我认为问题出在您使用findViewById()的过程中。findViewById()将在MorseKey视图本身而不是main.xml文件中查找资源。

也许可以尝试获取MorseKey实例的父实例并调用parent.findViewById().

case R.styleable.MorseKey_parentKey:
    parent = this.getParent().findViewById(a.getResourceId(attr, -1));

尽管只有当您的MorseKey父级和子级在同一布局中时,这才会起作用。

<LinearLayout ...>
     <MorseKey ..../><!-- parent -->
     <MorseKey ..../><!-- child -->
</LinearLayout>

但是,如果您的布局是这样的,父级和子级位于不同的布局中,则很难找到视图。

<LinearLayout ...>
     <MorseKey ..../><!-- parent -->
</LinearLayout>
<LinearLayout ...>
     <MorseKey ..../><!-- child -->
</LinearLayout>

最新更新