android getHeight()/getWidth with RelativeLayout

3

你好,我是一个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。


1
使用 View.post(new Runnable()); - Adil Soomro
请问您能否提供更多细节?我是Android的新手。谢谢! - boreas
location[1] 是Y坐标,我认为你需要X坐标 (location[0]) [http://developer.android.com/reference/android/view/View.html#getLocationOnScreen%28int[]%29]。 - beetstra
你是对的,但location[0]也是0。 - boreas
3个回答

4

您在视图布局完成之前调用了getHeight()/getWidth(),因此它返回0。如果您在生命周期的后期调用它,则可以解决此问题。


1

一旦您的视图被创建,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 会在加上一个固定值后给出按钮的宽度


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接