java - 在 RelativeLayout 中动态重新定位 View

标签 java android xml

我正在尝试动态地重新定位一个 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/

相关文章:

java - 使用相同的实现从数组列表创建对象

android - 模拟车速表

html - "Can' t 使用字符串 ( "") 作为 HASH 引用,而 "strict refs"在使用时出现“将哈希分配给 Perl 中的哈希时出错”

android - 资源xml文件中的数组是否有序?

javascript - 无法将下拉值传递给 XSLT 参数

java - 发送邮件时是否需要 TLS 身份验证凭据

java - 如何使用 com.microsoft.azure.storage.blob.CloudBlockBlob 的 upload()

java - 为什么在 Java 代码中实现单例模式(有时)被认为是 Java 世界中的反模式?

android - 如何为远程机器开发和本地设备部署设置 ADB

android - WebViewClient 中的 onPageFinished 似乎没有正确触发