Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Layout with child views

I am getting an error on this. Cannot figure out how to use child views in my custom view (Relative layout).

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

}

The problem is I keep on getting NPE when ever I try to use star or spinner. Dont know how to use the child views.

like image 585
Fahad Ishaque Avatar asked Oct 17 '25 04:10

Fahad Ishaque


1 Answers

You cannot find these views in constructor. The child views are not yet added to the parent.

For your case, you can override the addView() method and do the same :

@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;
    }
}
like image 167
Eldhose M Babu Avatar answered Oct 18 '25 19:10

Eldhose M Babu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!