2

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

我有一个main.xml包含其中一些的:

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

ares/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"(用加号),但也没有用。我究竟做错了什么?

4

1 回答 1

1

如果您的 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>
于 2012-03-08T22:15:04.430 回答