RiadSaadi
RiadSaadi

Reputation: 401

what is wrong in my program to add ImageView programmatically

I am using main.xml to add widgets to my activity, but for some reasons I want to add an imageView programmatically, this is my program,

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ImageView imageView = new ImageView(this);
        imageView.setImageResource(R.drawable.building_icon);
        imageView.getLayoutParams().height = 100 ;
        imageView.getLayoutParams().width = 100 ;
        imageView.setBackgroundColor(Color.BLACK);
        FrameLayout fl = new FrameLayout(this); // because I am working with frame layout
        fl.addView(imageView); 
        }

my imageView doesn't appear, please where I miss?

Upvotes: 2

Views: 150

Answers (2)

2Dee
2Dee

Reputation: 8627

You are inflating a content from xml with setContentView, then creating a new ImageView and adding it to a new FrameLayout that is not part of the original xml.

In order to add the ImageView to your FrameLayout, you need to first get a reference to the FrameLayout in your xml, using findViewById :

FrameLayout container = (FrameLayout) findViewById(R.id.frame_layout);

then you can add you ImageView to it using addView as you did :

container.addView(imageView); 

Upvotes: 1

Ken Wolf
Ken Wolf

Reputation: 23269

You've created a new FrameLayout and attached your ImageView to it but your FrameLayout is not attached to anything.

To reference the one in your main.xml do this:

FrameLayout fl = (FrameLayout) findViewById(R.id.my_frame_layout); 
fl.addView(imageView); 

Where it's defined in your main.xml like this:

<FrameLayout
    android:id="@+id/my_frame_layout"
    ... />

Upvotes: 2

Related Questions