我从一个示例zbar源代码继承了一个View类,但是我需要向这个View类添加一个ImageView,我没有这个视图的任何xml布局文件,所以如何添加这个ImageView动态地从代码?
public class AndroidBarcodeView extends View
{
static Context mContext;
public AndroidBarcodeView(Context context) {
super(context);
this.mContext = context;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
AndroidBarcodeTestActivite myActivity = (AndroidBarcodeTestActivite) getContext();
String id=myActivity.getString();
try {
} catch (Exception e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
您无法将View
添加到View
。您应该从RelativeLayout
,LinearLayout
,FrameLayout
或从ViewGroup
延伸的任何内容延伸。在那里,您可以致电addView()
,在那里您可以传递ImageView
。
关于布局,您可能希望从文档中阅读此页面:http://developer.android.com/guide/topics/ui/declaring-layout.html。这也解释了所有*Layout
类所做的事情。
看起来像这样(我复制了你的代码并对其进行了改编):
public class AndroidBarcodeView extends FrameLayout
{
// static Context mContext;
// Please do not do this with a Context, as it might leak and you'll get memory problems
// Also, the Context is available via getContext()
private ImageView img;
public AndroidBarcodeView(Context context) {
super(context);
ImageView img = new ImageView(context);
addView(img); // This adds the ImageView to the ViewGroup
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
AndroidBarcodeTestActivite myActivity = (AndroidBarcodeTestActivite) getContext();
String id=myActivity.getString();
try {
} catch (Exception e) {
e.printStackTrace();
}
}
}