以编程方式显示ImageView

时间:2011-05-30 21:13:48

标签: android android-imageview

当用户点击按钮时,如何让ImageView出现在屏幕中间?我已将图像放在res / drawable-folder中。

我一直在尝试使用下面的代码,但我不知道如何使ImageView出现:

 View v = new ImageView(getBaseContext());
 ImageView image; 
 image = new ImageView(v.getContext()); 
 image.setImageDrawable(v.getResources().getDrawable(R.drawable.gameover));

谢谢!

4 个答案:

答案 0 :(得分:112)

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

答案 1 :(得分:25)

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

答案 2 :(得分:7)

如果您添加到 RelativeLayout ,请不要忘记设置imageView的位置。例如:

datalabs.data.SQLStatement

答案 3 :(得分:-7)