0

我正在我的项目中创建一个 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) 后创建图像,这可能是原因吗?如果是,我如何“刷新”布局以包含图像但不对现有视图进行任何更改?

4

2 回答 2

0

以下可以工作:

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);
于 2015-04-01T19:52:37.057 回答
0

使用LayoutInflator基于您的布局模板创建视图,然后将其注入到您需要的视图中。

 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));
于 2016-05-12T13:42:32.540 回答