我正在尝试在代码中创建一个ImageView,设置图像资源,然后将ImageView作为子视图添加到我的主视图中。我发现的所有示例都使用了布局。但在我的观点的构造函数中,我无法弄清楚如何做到这一点。
以下是代码段:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new CanvasView(this));
}
}
观点:
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?
}
}
答案 0 :(得分:1)
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);
}
}
请记住,如果您需要直接从您需要的xml文件中为视图充气,对于MyContainer
和CanvasView
,构造函数将作为参数Context
和AttributeSet
答案 1 :(得分:1)
这取决于您使用的布局,这里是一些代码,所有视图都是以编程方式创建的。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
rootLayout.setOrientation(LinearLayout.VERTICAL);
ImageView imageView = new ImageView(getApplicationContext());
imageView.setImageResource(R.drawable.sample);
rootLayout.addView(imageView);
setContentView(rootLayout);
}