android getHeight()/getWidth 与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。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您在布局视图之前调用 getHeight()/getWidth(),因此它返回 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.
一旦创建了视图,UIThread 就会膨胀它们。因此,当您实例化它们时,它们没有大小。
尝试使用
但不确定它是否有效
Once your views are created, the UIThread inflates them. So when you instanciate them they have no size.
try using
Not sure if it'll work though
该 len 将在加上固定值后给出按钮宽度
This len will give buttons width after plus a fixed value