2016-07-25 13 views
1

私はある種の方法で2つのイメージを表示するはずのカスタムクラスを作成しています。カスタムビューからfindViewByIdを呼び出すとnullが返されます

私のXMLファイル:

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

    <com.kupol24.app.presentation.view.customViews.MyImageLayout 
     android:id="@+id/image_view" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"> 

     <ImageView 
      android:id="@+id/pattern" 
      android:layout_height="wrap_content" 
      android:layout_width="wrap_content" 
      android:src="@drawable/start_pattern" 
      android:layout_alignParentLeft="true" 
      android:layout_alignParentTop="true"/> 

     <ImageView 
      android:id="@+id/logo" 
      android:layout_height="wrap_content" 
      android:layout_width="wrap_content" 
      android:src="@drawable/start_logo" 
      android:layout_centerInParent="true" 
      android:layout_centerVertical="true"/> 
    </com.kupol24.app.presentation.view.customViews.MyImageLayout> 

</RelativeLayout> 

とクラス自体:ここに私のコードのいくつかの選択された部分です

public class MyImageLayout extends RelativeLayout { 

    private ImageView patternImage, logoImage; 
    private Bitmap pattern, logo; 

    public MyImageLayout (Context context, AttributeSet attrs) { 
     super(context, attrs); 

     patternImage = (ImageView) findViewById(R.id.pattern); 
     logoImage = (ImageView) findViewById(R.id.logo); 

     pattern = ((BitmapDrawable) patternImage.getDrawable()).getBitmap(); 
     logo = ((BitmapDrawable) logoImage.getDrawable()).getBitmap(); 

     pattern = Bitmap.createScaledBitmap(pattern, patternDiameter, patternDiameter, false); 
     logo = Bitmap.createScaledBitmap(logo, logoDiameter, logoDiameter, false); 
    } 
} 

は私が手の問題は、findViewByIdがnullを返すということです、代わりに与えますイメージビュー。どうすればこの問題を解決できますか?ありがとう

+0

ViweをMyImageLayout()コンストラクタ – vinoth12594

+0

に渡し、patternImage =(ImageView)view.findViewById(R.id.pattern);を使用します。 – vinoth12594

+0

サブビューを初期化するには、onFinishInflate()メソッドを使用することをお勧めします。 –

答えて

3

私が得意な問題は、findViewByIdが の代わりにnullを返し、ImageViewを与えているということです。どうすればこの問題を解決できますか?

カスタムレイアウトの子が追加されているという保証はありません。 ViewGroupはonFinishInflateコールバックを持っています。これは、ドキュメンテーションが示すように、すべての子ビューが追加された後、インフレーションの最後のフェーズとして呼び出されます。このコールバックをオーバーライドし、そこでfindViewByIdコールを移動します。

関連する問題