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