user3640774
user3640774

Reputation: 21

Trying to create imageView when click the button

I am trying to create ImageView when I click the button.I don't know why when I am creating it I get the error on new Image.

the code I am working is as follows:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button save;

    save = (Button) findViewById(R.id.savebtn);

    save.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            ImageView image = new ImageView(activity_main,this);
            RelativeLayout mylayout = (RelativeLayout) findViewById(R.id.container);
            image.setBackgroundResource(R.drawable.element_wall);
            mylayout.addView(image);

        }
    });

As I sayd I am getting error on this line: ImageView image = new ImageView(activity_main,this); I have tryed to put only this but not working, I am using activity_main.

Upvotes: 0

Views: 1271

Answers (2)

User12111111
User12111111

Reputation: 1219

Please check the constructor of ImageView here

Your code should look like:

  ImageView image = new ImageView(<YourActivityClass>.this);

Upvotes: 0

Piyush
Piyush

Reputation: 18923

I don't know that you posted wrong or right or typing mistake but according to your code it should be

 ImageView image = new ImageView(activity_main,this);

to

 ImageView image = new ImageView(activity_main.this);

also you can use

 image.setImageResource(R.drawable.element_wall);

instead of

 image.setBackgroundResource(R.drawable.element_wall);

Upvotes: 1

Related Questions