Show ImageView programmatically

前端 未结 4 653
北荒
北荒 2020-12-05 01:51

How can I make an ImageView appear in the middle of the screen when the user clicks a button? I have placed the image in the res/drawable-folder.

I\'ve been trying w

相关标签:
4条回答
  • 2020-12-05 01:55
    //LinearLayOut Setup
    LinearLayout linearLayout= new LinearLayout(this);
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    
    linearLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
    LayoutParams.MATCH_PARENT));
    
    //ImageView Setup
    ImageView imageView = new ImageView(this);
    
    //setting image resource
    imageView.setImageResource(R.drawable.play);
    
    //setting image position
    imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 
    LayoutParams.WRAP_CONTENT));
    
    //adding view to layout
    linearLayout.addView(imageView);
    //make visible to program
    setContentView(linearLayout);
    
    0 讨论(0)
  • 2020-12-05 02:03
    • Create the ImageView
    • Use an OnClickListener in the button
    • Add the ImageView to the layout or set the visibility of the ImageView to VISIBLE
    0 讨论(0)
  • 2020-12-05 02:03

    If you add to RelativeLayout, don't forget to set imageView's position. For instance:

    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(200, 200);
    lp.addRule(RelativeLayout.CENTER_IN_PARENT); // A position in layout.
    ImageView imageView = new ImageView(this); // initialize ImageView
    imageView.setLayoutParams(lp);
    // imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
    imageView.setImageResource(R.drawable.photo);
    RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout);
    layout.addView(imageView);
    
    0 讨论(0)
  • 2020-12-05 02:14
    int id = getResources().getIdentifier("gameover", "drawable", getPackageName());
    ImageView imageView = new ImageView(this);
    LinearLayout.LayoutParams vp = 
        new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
                        LayoutParams.WRAP_CONTENT);
    imageView.setLayoutParams(vp);        
    imageView.setImageResource(id);        
    someLinearLayout.addView(imageView); 
    
    0 讨论(0)
提交回复
热议问题