【问题标题】:Dynamically reposition view in RelativeLayout在 RelativeLayout 中动态重新定位视图
【发布时间】:2014-03-03 21:22:42
【问题描述】:

我正在尝试动态地重新定位视图(其中包含画布元素)。这个想法是让用户触摸盒子并能够在屏幕上拖动它。我打算抓住 touch motion_events 以重新定位用户拖动的块。这是我目前拥有的代码,我认为它可以工作,但到目前为止还没有产生任何成功。

int[] coords = getLastLocations();

setContentView(R.layout.activity_main);

View mainv = findViewById(R.id.mainRelativeLayout);
BoxView bvr = (BoxView) findViewById(R.id.BoxViewRed);
BoxView bvb = (BoxView) findViewById(R.id.BoxViewBlue);
bvr.setColor(255, 0, 0);
bvr.layout(coords[0], coords[1], 60, 60);
bvb.setColor(0, 0, 255);
bvb.layout(coords[2], coords[3], 60, 60);

mainv.invalidate();

任何有关如何使此代码工作的提示或其他方法都是完美的。

附:针对 ICS+ (API 14-19)

【问题讨论】:

标签: java android xml


【解决方案1】:

找到答案,

您可以在视图上使用 setX 和 setY 动态定位视图。例如,固定代码如下所示:

    int[] coords = getLastLocations();

    setContentView(R.layout.activity_main);

    View mainv = findViewById(R.id.mainRelativeLayout);
    BoxView bvr = (BoxView) findViewById(R.id.BoxViewRed);
    BoxView bvb = (BoxView) findViewById(R.id.BoxViewBlue);

    bvr.setColor(255, 0, 0);
    bvr.setX(coords[0]);
    bvr.setY(coords[1]);
    bvb.setColor(0, 0, 255);
    bvb.setX(coords[2]);
    bvb.setY(coords[3]);

请记住,这会将元素定位为像素值,如果您将 DIP 用于您的视图等,您可能需要进行单位转换以使一切看起来正确。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多