Android没有以编程方式创建ImageView

时间:2015-04-01 19:08:06

标签: android layout view imageview setcontentview

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

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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));