I'm trying to create an ImageView in code, setting the image resource and then add the ImageView as a child-view to my main view. All examples I found used a layout for that. But inside the constructor of my view I can't figure out how to do that.
Here are the code snippets:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new CanvasView(this));
}
}
The view:
public class CanvasView extends SurfaceView implements SurfaceHolder.Callback {
public CanvasView(Context context) {
super(context);
SurfaceHolder sh = getHolder();
sh.addCallback(this);
ImageView iv = new ImageView(context);
iv.setImageResource(R.drawable.wand);
// how to add iv to myself?
}
}
you can not do that this way. you need a container for both: For instance
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyContainer(this));
}
}
public class MyContainer extends LinearLayout {
public MyContainer(Context context) {
addView(new CanvasView(context));
ImageView iv = new ImageView(context);
iv.setImageResource(R.drawable.wand);
addView(iv);
}
}
remember that if you need to inflate the view directly from a xml file you need, for both MyContainer
and CanvasView
the constructor thats takes as parameters Context
and AttributeSet
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With