簡體   English   中英

在RelativeLayout中動態重新放置視圖

[英]Dynamically reposition view in RelativeLayout

我試圖動態地重新定位視圖(包含畫布元素)。 想法是讓用戶觸摸該框並能夠在屏幕上拖動它。 我打算抓住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();

關於如何使此代碼正常工作或其他方法的任何提示都將是完美的。

PS定位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等,則可能需要進行單位轉換,以使所有內容看起來正確。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM