问题
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