2016-07-24 17 views
1

xmlの属性からIDからビューを取得したいとします。私はgetParent()で試しましたが、返品はnullです。カスタムビュークラスの属性からIDでビューを取得

<RelativeLayout 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:ntwldg="http://schemas.android.com/apk/res-auto" 
     android:orientation="vertical" 
     android:background="@drawable/background_settings" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 

    <TextView 
      android:id="@+id/revealView" 
      android:gravity="center" 
      android:text="TEST" 
      android:background="@android:color/darker_gray" 
      android:visibility="invisible" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent"/> 

    <com.dot.networkloading.NetworkLoading 
      android:id="@+id/network_loading" 
      ntwldg:text="Youtube" 
      ntwldg:image="@drawable/ic_youtube" 
      ntwldg:imageBackground="@drawable/ic_youtube" 
      ntwldg:revealView="@id/revealView" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent"/> 
</RelativeLayout> 

attributerevealView

XMLは、上記Viewを参照しています。

コード - NetworkLoading(INIT())

 title = (TextView) findViewById(R.id.title); 
     image = (ImageView) findViewById(R.id.image); 
     imageBackground = (ImageView) findViewById(R.id.imageBackground); 
     finishView = findViewById(R.id.revealView); 

     String text = attributes.getString(R.styleable.network_loading_text); 
     imageId = attributes.getResourceId(R.styleable.network_loading_image, 0); 
     imageBackgroundId = attributes.getResourceId(R.styleable.network_loading_imageBackground, 0); 

     finishView = ((View) getParent()).findViewById(attributes.getResourceId(R.styleable.network_loading_revealView, R.id.revealView)); 
+0

あなたが何を求めているのかは、はっきりしていません。 'NetworkLoading''の' View'への参照を取得しようとしていて、 'findViewById(R.id.revealView)'がその 'TextView'を正常に返すのであれば、' findViewById(R.id.network_loading) 'はあなたに 'NetworkLoading''' View'を与えてください。 –

+0

@MikeM。このIDをxmlから渡してNetworkLoadingからR.id.revealViewを取得したいとします。 –

+0

ああ、今、私はつまずいた。そのコードはどこにありますか? 'NetworkLoading'のコンストラクタに入っていますか? –

答えて

2

あなたがあまりにも早くあなたのrevealViewを見つけるためにしようとしているようです。コンストラクタでは、Viewがまだレイアウトに追加されていないので、getParent()nullを返します。 revealViewのリソースIDをフィールドとして保持し、その値をコンストラクタで取得し、onAttachedToWindow()メソッドのViewを探します。

投稿したコードでは、最後の行、最後のfinishView = ...行を削除し、リソースIDをフィールドに保存してください。

revealViewId = attributes.getResourceId(R.styleable.NetworkLoading_revealView, R.id.revealView); 

そして、代わりにonAttachedToWindow()方法でViewを見つけます。

@Override 
protected void onAttachedToWindow() { 
    super.onAttachedToWindow(); 

    finishView = ((View) getParent()).findViewById(revealViewId); 
    ... 
} 
+1

それは動作します、ありがとう。 –

関連する問題