带有RelativeLayout的android getHeight()/ getWidth

时间:2011-09-28 14:37:11

标签: android position relativelayout

您好我是Android的新手并且遇到了问题:如何获得视图的高度/宽度,该视图位于相对布局中?我尝试了getHeight()和getWidth(),并且都返回0。

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

或者在不知道当前视图的位置的情况下,有更好的方法可以做到这一点吗?

编辑: 我使用此代码创建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。

3 个答案:

答案 0 :(得分:4)

您在调用视图之前调用getHeight()/ getWidth(),因此它返回0.如果您在生命周期的后期调用它,它将停止此问题。

答案 1 :(得分:1)

创建视图后,UI线程会对它们进行充气。因此,当您实例化它们时,它们没有大小。 尝试使用

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

不确定它是否会起作用

答案 2 :(得分:0)

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

此len将在加上固定值后给出按钮宽度