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" />

これらのいずれかを含むa 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 == 2parent == nullparent == nullcustom:parentKey="@+id/be"

4

1 に答える 1

1

あなたのMorseKeyクラスが別のJavaファイルにある場合、それはあなたのステートメント「クラス(私の活動ではない)」の場合であると私は思います。次に、問題はfindViewById()の使用にあると思います。findViewById()は、main.xmlファイルではなく、MorseKeyビュー自体の中でリソースを検索します。

たぶん、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 に答える