2011-10-03 74 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); 
相关问题