android getHeight()/getWidth with RelativeLayout

∥☆過路亽.° 提交于 2019-12-02 02:22:07

问题


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];
            curView.getLocationOnScreen(location);
            Log.d("right:", String.valueOf(location[1]));

and it shows a 0.


回答1:


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.




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/7584957/android-getheight-getwidth-with-relativelayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!