2011-10-03 69 views
0

我想在屏幕中間水平和垂直繪製一個簡單的ImageView。但是我想在不使用XML文件的情況下做到這一點,我需要以編程方式完成它。如何在屏幕中間畫一個ImageView? (以編程方式)

我嘗試了下一個代碼,但它不能正常工作,它將圖像稍微向右和稍向底部繪製。如何解決它?

ARImage = new ImageView(getApplicationContext()); 
    ARImage.setImageResource(R.drawable.x); 
    rl.addView(ARImage); //rl is the relative layout that it's inserted into a frame layout 

    Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
    int w = display.getWidth(); 
    int h = display.getHeight(); 
    RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    position.leftMargin = (int)(w/2); 
    position.topMargin = (int)(h/2); 
    ARImage.setLayoutParams(position); 
+0

您是否在使用內容視圖的任何佈局? –

+0

我不明白你的意思,我使用相對佈局,在代碼中註釋,以及它在framelayout內的相對佈局。 – NullPointerException

+0

你能顯示你的xml代碼嗎? –

回答

2

它適用於我這樣的:

package pete.android.study; 

import android.app.Activity; 
import android.content.Context; 
import android.os.Bundle; 
import android.view.Display; 
import android.view.WindowManager; 
import android.widget.ImageView; 
import android.widget.RelativeLayout; 
import android.widget.RelativeLayout.LayoutParams; 


public class Main extends Activity { 

    /* 
    * (non-Javadoc) 
    * @see android.app.Activity#onCreate(android.os.Bundle) 
    */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     ImageView ARImage = new ImageView(getApplicationContext()); 
     ARImage.setImageResource(R.drawable.icon); 
     RelativeLayout rl = new RelativeLayout(this); 
     Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
     int w = display.getWidth(); 
     int h = display.getHeight(); 
     RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
     ARImage.setLayoutParams(position); 

     position.addRule(RelativeLayout.CENTER_IN_PARENT); 
     rl.addView(ARImage, position); 
     setContentView(rl); 
    } 

} 
+0

現在getWidth和getHeight折舊。 – Xitcod13

1

嘗試使用

position.leftMargin = (int)(w/2 - whalf); 
position.topMargin = (int)(h/2 - hhalf); 

其中whalfhhalf是你的圖像參數的半區。

0

我不認爲你可以設置左,上邊距那樣:

position.leftMargin = (int)(w/2); 
position.topMargin = (int)(h/2); 

嘗試設置頁邊距是這樣的:

position.setMargins((int)(w/2), (int)(h/2), 0, 0); // left, top, right, bottom 
0

知道它的RelativeLayout的裏面,你可以把它放置在這個佈局的中心:

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    lp.addRule(RelativeLayout.CENTER_IN_PARENT); 
    rl.addView(ARImage, lp); 
相關問題