在相对布局中动态重新定位视图



我正在尝试动态重新定位视图(其中包含画布元素)。这个想法是让用户触摸框并能够在屏幕上拖动它。我打算抓住触摸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)

找到答案,

您可以使用 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 用于视图等,您可能需要进行单位转换才能使一切看起来正确。

最新更新