具有子视图的自定义布局

Fah*_*que 2 android android-custom-view

我对此有误。无法弄清楚如何在我的自定义视图(相对布局)中使用子视图。

   <RelativeLayout >   

    <com.xxxxxx.FavouriteImageView
        android:id="@+id/favorite_status"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="15dp"
        android:clickable="true" >

        <ImageView
            android:id="@+id/favourite_iv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/yellow_star"
            android:clickable="false" />

        <ProgressBar
            android:id="@+id/favorite_spinner"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone"
            android:clickable="false" />

    </com.xxxxxxxx.FavouriteImageView>
Run Code Online (Sandbox Code Playgroud)

public class FavouriteImageView extends RelativeLayout{

ImageView star;
ProgressBar spinner;
boolean isFavorite;

Context context;

public FavouriteImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    this.context= context;
    findChildViews();}

public FavouriteImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.context= context;
    findChildViews();
}

public FavouriteImageView(Context context) {
    super(context);
    this.context= context;
    findChildViews();}


private void findChildViews(){

    star = (ImageView) findViewById(R.id.favourite_iv);
    spinner = (ProgressBar) findViewById(R.id.favorite_spinner);
}
Run Code Online (Sandbox Code Playgroud)

}

问题是,无论何时尝试使用star或,我都会不断获得NPE spinner。不知道如何使用子视图。

Eld*_*abu 5

您无法在构造函数中找到这些视图。子视图尚未添加到父视图。

对于您的情况,您可以覆盖addView()方法并执行以下操作:

@Override
public void addView(View child, int index, LayoutParams params) {
    super.addView(child, index, params);
    switch (child.getId()) {
    case R.id.favourite_iv:
        spinner = (ProgressBar) child;
        break;
    case R.id.favorite_spinner:
        star = (ImageView) child;
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)