2011-09-28 85 views
2

嗨,我是新来的Android和面临的问题:我如何得到一个视图的高度/宽度放置在相对布局?我试过getHeight()和getWidth(),两者都返回0.android getHeight()/ getWidth与RelativeLayout

我需要知道此视图是否已达到布局的末端,以便我可以将下一个视图置于其右侧或下方。

或者有没有更好的方法来做到这一点,而不知道当前视图的位置?

编辑: 我用这个代码来创建一个EditText,并将其添加到布局:

   EditText et1 = new EditText(context); 
       RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 
         ViewGroup.LayoutParams.WRAP_CONTENT); 
       p.addRule(RelativeLayout.RIGHT_OF,curView.getId()); 
       et1.setLayoutParams(p); 
       et1.setId(loopid++); 
       curLayout.addView(et1); 
       curView=et1; 

,然后调用:

  int[] location=new int[2]; 
      curView.getLocationOnScreen(location); 
      Log.d("right:", String.valueOf(location[1])); 

,它显示了一个0

+1

使用'View.post(新的Runnable()) ;' –

+0

可以请你提供更多的细节?我是Android新手。谢谢! – boreas

+0

'location [1]'是Y坐标,我认为你需要X坐标('location [0]')[http://developer.android.com/reference/android/view/View.html#getLocationOnScreen% 28int []%29] – beetstra

回答

4

在布局视图之前,您正在调用getHeight()/ getWidth(),因此它返回0.如果在生命周期的较后阶段调用它,则会停止此问题。

+0

不,我不是,看到新的编辑。 – boreas

0

一旦你的观点被创建,UIThread膨胀他们。所以当你把它们装上时,它们没有大小。 尝试使用

ViewTreeObserver vto = curView.getViewTreeObserver(); 
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() 
{ 
    public boolean onPreDraw() 
    { 
     curView.getLocationOnScreen(location); 
    } 
} 

不知道它会工作虽然

0
final Button button = new Button(this); 
button.setText("123"); 
TextPaint paint = button.getPaint(); 
float len = paint.measureText(button.getText().toString()); 

这LEN会给按钮后宽度加上一个固定值

相关问题