Trying to create imageView when click the button

坚强是说给别人听的谎言 提交于 2019-12-13 03:51:34

问题


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.


回答1:


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



回答2:


Please check the constructor of ImageView here

Your code should look like:

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


来源:https://stackoverflow.com/questions/23805711/trying-to-create-imageview-when-click-the-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!