Android 不显示以编程方式创建的 ImageView

Android not showing programmatically created ImageView

我正在我的项目中创建一个 ImageView,如下所示:

RelativeLayout root = (RelativeLayout) ((Activity) GameGuessActivity.context).findViewById(R.id.layout);
ImageView img = new ImageView(GameGuessActivity.context);

img.setImageResource(R.drawable.image);

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);
params.leftMargin = x;
params.topMargin = y;
root.addView(img, params);

但是图像没有显示。我在调用 setContentView(R.layout.layout) 之后创建图像,这可能是原因吗?如果是,我如何 'refresh' 包含图像但不对现有视图进行任何更改的布局?

以下可以工作:

View root = getLayoutInflater.inflate(your_layout, null);
ImageView img = new ImageView(GameGuessActivity.context);
img.setImageResource(R.drawable.image);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);
params.leftMargin = x;
params.topMargin = y;
root.addView(img, params);
setContentView(root);

Use the LayoutInflator to create a view based on your layout template, and then inject it into the view where you need it.

 LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = vi.inflate(R.layout.your_layout, null);

// fill in any details dynamically here
TextView textView = (TextView) v.findViewById(R.id.a_text_view);
textView.setText("your text");

// insert into main view
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.insert_point);
insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));