3

ActionButton というカスタム ボタンを作成しましたが、並列ビュー階層にある別のビューへの参照を取得しようとしています。を使おうと思ったのですfindViewById(int id)が、取得し続けていたNullPointerExceptionsので、 経由で RootView への参照を取得しgetRootView()、そこから でビューを取得しようとしましたfindViewById(int id)。問題はgetRootView、レイアウトまたは null を返す代わりに、そのメソッドを呼び出した ActionButton を返すことです。

これが私のActionButtonで、参照を取得しようとしています:

public class ActionButton extends Button {

    protected void onFinishInflate(){
        super.onFinishInflate();
        log(getRootView() == this)    //true, what I don't understand...
        ConnectionLayer connectionLayer = (ConnectionLayer) findViewById(R.id.connection_layer);  //Returns null...
    }
}

私のlayout.xmlファイルの概要:

<FrameLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent" >

  <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

      (much more xml elements)

      <com.cae.design.reaction.ui.ActionButton
            android:id="@+id/actionButton"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:layout_gravity="center_vertical" />

   </LinearLayout>

   <com.cae.design.reaction.ui.ConnectionLayer
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/connection_layer"
      android:layout_width="match_parent"
      android:layout_height="match_parent" >
   </com.cae.design.reaction.ui.ConnectionLayer>

</FrameLayout>

getRootViewビュー自体を返す理由を説明していただければ幸いです。または、他の方法で参照する方法のヒントを教えていただければ幸いです。

4

3 に答える 3

2

getRootView メソッドのソース コードを見ると、次のようになります。

 public View getRootView() {
        if (mAttachInfo != null) {
            final View v = mAttachInfo.mRootView;
            if (v != null) {
                return v;
            }
        }

        View parent = this;

        while (parent.mParent != null && parent.mParent instanceof View) {
            parent = (View) parent.mParent;
        }

        return parent;
    }

このメソッドがそれ自体を返す唯一のケースは、ビューがビュー階層にアタッチされておらず (および mAttachInfo.mRootView が null ではない)、親を持たないか、親が View インスタンスではない場合です。 . よろしくお願いします。

于 2012-06-14T13:34:50.123 に答える
0

代わりにgetParent()を呼び出してみてViewGroup、必要に応じて結果をキャストしてください。getChildCount()次に、 と を使用して他の子ビューにアクセスできますgetChildAt()

于 2012-05-29T15:41:21.583 に答える
0

getRootView() はそれ自体を返します。これは、ActionButton の iflating が終了した時点で親が終了していないためです。つまり、getRootView() を呼び出すと、ActionButton は LinearLayout に接続されません。ルート ビューが必要な場合は、次のようにします。

new Thread(new Runnable() {

    @Override
    public void run()
    {
                    // wait until LinearLayout will finish inflating and this
                    // view will be connected to it
        while(getRootView() == this) {} 
        // do your buisness now
    }
}).start();
于 2013-04-20T09:10:31.653 に答える