开发者

android getHeight()/getWidth with RelativeLayout

Hi I'm new to Android and am facing the problem: how do I get the Height/Width of a view, which is placed in a relative layout? I tried getHeight() and getWidth() and both return 0.

I need to know whether this view has reached the end of the Layout so that I can place the next view to its right or below it.

or maybe there is a better way to do this without knowing the position of the current view?

edit: I use this code to create an EditText and add it to the layout:

                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;

and then call:

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

and it shows a 0.


You are calling getHeight()/getWidth() before the view can be laid out so it is returning 0. If you call it later in the lifecycle it will stop this issue.


Once your views are created, the UIThread inflates them. So when you instanciate them they have no size. try using

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

Not sure if it'll work though


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

This len will give buttons width after plus a fixed value

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜