2011-05-30 36 views
51

當用戶單擊按鈕時,如何讓ImageView出現在屏幕中間?我已將圖像放在res/drawable文件夾中。以編程方式顯示圖像查看

我一直在試圖與下面的代碼,但我不知道如何使ImageView的出現:

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

謝謝!

回答

-2
+43

不是很有幫助。應該說明「檢查文檔」 – phlebotinum 2014-05-29 15:25:09

+25

太模糊......「1)學習java 2)閱讀android文檔」也可以。 – Josh 2014-11-13 10:13:33

+9

WOw,苛刻。我認爲他的回答寫得很好,並使用適當的鏈接來回答這個問題。 – FuriousFolder 2014-11-14 20:01:43

23
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); 
93
//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); 
4

如果添加到OnClickListener RelativeLayout,不要忘記設置imageView的位置。例如:

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(200, 200); 
lp.addRule(RelativeLayout.CENTER_IN_PARENT); // A position in layout. 
imageView.setLayoutParams(lp); 
// imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); 
imageView.setImageResource(R.drawable.photo); 
RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout); 
layout.addView(imageView);