Reputation: 99
I got a custom class that extends View. I want to have a imageview in this class which should be the size of the View, so when I add the View to a layout it would show the imageview for the View. My problem is, that I can't change the size of the imageview.
public class CustomView extends View{
ImageView imageView;
public CustomView(Context context, float ivSize) {
super(context);
imageView = new ImageView(context);
//change size of imageView here
}
What I tried:
LinearLayout.LayoutParams imgvwDimens =
new LinearLayout.LayoutParams((int)ivSize, (int)ivSize);
imageView.setLayoutParams(imgvwDimens);
-nothing
android.view.ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
layoutParams.width = (int)ivSize;
layoutParams.height = (int)ivSize;
imageView.setLayoutParams(layoutParams);
-nullpointer for layoutParams.width & layoutParams.height
imageView.setLayoutParams(new LayoutParams((int)ivSize, (int)ivSize));
-nothing
imageView.requestLayout();
imageView.getLayoutParams().height = (int)ivSize;
imageView.getLayoutParams().width = (int)ivSize;
-nullpointer for .width & .height
I get that there might be no params yet because I don't use a imageview from xml, but that only explains case 2 and 4. I don't get why 1 and 3 do nothing and I don't know what else I could try. What am I missing?
Edit: Solution
Works now, I extended RelativeLayout instead of View, added the imageView in the constructor like this:
this.addView(imageView);
and implemented
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
imageView.layout(0, 0, ivSize, ivSize);
}
Thanks guys!
Upvotes: 0
Views: 1544
Reputation: 93559
You need to make a custom ViewGroup rather than a custom view if you want it to contain another view. Typically if you do this you extend either RelativeLayout or LinearLayout, so all of the laying out code is written and you would set the appropriate type of LayoutParams. You also have to add the ImageView to the custom ViewGroup via addView
Upvotes: 1