我正在尝试动态地重新定位一个 View (其中包含一个 Canvas 元素)。这个想法是让用户触摸框并能够在屏幕上拖动它。我打算捕获触摸 motion_events 以重新定位用户拖动的 block 。这是我目前拥有的代码,我认为它可以工作,但到目前为止还没有取得任何成功。
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)
最佳答案
找到答案,
您可以在 View 上使用 setX 和 setY 动态定位 View 。例如,固定代码如下所示:
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 用于 View 等,则可能需要进行单位转换才能使一切看起来正确。
关于java - 在 RelativeLayout 中动态重新定位 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22157734/