具有子视图的自定义布局

时间:2014-11-17 10:27:43

标签: 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>

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);
}

}

问题是,当我尝试使用starspinner时,我会继续获取NPE。不知道如何使用子视图。

2 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:2)

尝试在自定义布局类中使用它:

@Override
public void addView(@NonNull View child, int index, ViewGroup.LayoutParams params) {
    super.addView(child, index, params);
    if (child.getId() == R.id.favourite_iv) {
        star = findViewById(R.id.favourite_iv);
    } else if (child.getId() == R.id.favorite_spinner) {
        spinner = findViewById(R.id.favourite_spinner);
    }
}