androidlayoutviewimageviewsetcontentview

Android not showing programmatically created ImageView


I am creating an ImageView in my project like this:

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);

But the Image is not displaying. I am creating the image after the setContentView(R.layout.layout) is being called, could that be the reason? If yes, how can I 'refresh' the layout to include the image but not change anything to existing Views?


Solution

  • The following could work:

    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);