问题
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