2012-03-08 4 views
2

オブジェクト間の関係階層を設定しようとしています。すべてのオブジェクトは、それ自身と同じタイプの親を持ちます。つまり、nullです。Android:attrs.xmlからのオブジェクト参照付きのカスタムビュー。常に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(悪い)を報告します。 More、parent == null私は明示的に何らかの値に設定しようとしています(コメント参照)。私もcustom:parentKey="@+id/be"(プラス記号付き)を試しましたが、それもうまくいきませんでした。私は間違って何をしていますか?

答えて

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> 
+0

私はAPIに注意を払うように教えてください。 this.getRootView()を呼び出すと、すべてのMorseKeyが独自のルートビューになります。 – mkjeldsen

+0

ああ!コンストラクタからgetParent()を呼び出すのが早すぎると、ビューは親ビューにまだ追加されていません。私はコールを遅らせることができ、それを動作させることができました。 – mkjeldsen

関連する問題