relativelayout运行时中的位置视图

发布于 2024-12-20 14:16:28 字数 619 浏览 2 评论 0原文

我想向相对布局添加一个视图。 该视图必须添加到指定位置。

我有这个:

    int x = ...;
    int y = ...;
    button.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            int x = (int) event.getRawX();
            int y = (int) event.getRawY();
            v.layout(x, y, x + v.getWidth(), y + v.getHeight());
            return true;
        }
    });
    relativelayout.addView(button);
    button.layout(x, y, x + button.getWidth(), y + button.getHeight());

ontouchlistener 效果很好..视图保持在我的手指上。 然而起始位置始终是 0, 0...我的 x 和 y 是什么并不重要。

有人有想法吗?

i want to add a view to a relativelayout.
this view must be added to a specified position.

i have this:

    int x = ...;
    int y = ...;
    button.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            int x = (int) event.getRawX();
            int y = (int) event.getRawY();
            v.layout(x, y, x + v.getWidth(), y + v.getHeight());
            return true;
        }
    });
    relativelayout.addView(button);
    button.layout(x, y, x + button.getWidth(), y + button.getHeight());

the ontouchlistener works great.. the view stays with my finger.
however the startpostion is always 0, 0... it doesn't matter what my x and y is.

anyone a idee?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不可一世的女人 2024-12-27 14:16:28

在将按钮添加到父视图之前,您可能需要尝试设置按钮的位置。所以只需交换这两行:

relativelayout.addView(button);
button.layout(x, y, x + button.getWidth(), y + button.getHeight());

就可以了:

button.layout(x, y, x + button.getWidth(), y + button.getHeight());
relativelayout.addView(button);

You might want to try setting the position of your button before you add it to the parent view. So just swap these two lines:

relativelayout.addView(button);
button.layout(x, y, x + button.getWidth(), y + button.getHeight());

to be this:

button.layout(x, y, x + button.getWidth(), y + button.getHeight());
relativelayout.addView(button);
土豪 2024-12-27 14:16:28

我有一个解决方法。

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
lp.leftMargin = x;
lp.topMargin = y;
relativelayout.addView(tmpTextButtonView, lp);

使用边距来定位浮动视图并不是很好。然而它对我有用。

i have a workaround.

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
lp.leftMargin = x;
lp.topMargin = y;
relativelayout.addView(tmpTextButtonView, lp);

it is not great to use margin for positioning floating views. however it works for me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文