2011-11-30 151 views
3

我有一個應用程序充滿了Android的自定義按鈕。我想讓用戶重新排列這些按鈕,如家或應用程序面板的圖像按鈕。使用x,y座標查找佈局

我研究了這一點,發現我可以使用拖放功能與用戶的運動進行交互。但在我的情況下,父母的佈局可能不同。 OnMove或OnDrop事件,我需要實際移動那個按鈕在相應的佈局。

所以問題是我如何找到包含座標x & y的佈局,並將按鈕放入其中。

@Override 
public boolean onTouchEvent(MotionEvent event) { 


    switch (event.getAction()) { 
    case MotionEvent.ACTION_DOWN: 
     status = START_DRAGGING; 
     break; 
    case MotionEvent.ACTION_UP: 
     status = STOP_DRAGGING; 
     break; 
    case MotionEvent.ACTION_MOVE: 
     if(status == START_DRAGGING){ 
      //parentLayout.setPadding((int)event.getRawX(), 0,0,0); 
      //**What to do here** 
      parentLayout.invalidate(); 
     }       
     break; 

    } 

    return true; 
} 
+0

我希望你不能使用佈局xml文件,因此與移除啓動,並找到一個功能按鈕基於x,y座標或細胞在表。 –

+0

我明白你的意思。嗯......我有一百個左右的按鈕,所以這將是重大改變。 –

回答

8

您可以通過所有控件在父容器循環,每個孩子的界限與當前的X相比,Y.你可以通過調用得到一個觀點界限這樣的:

View.getHitRect()

因此,像這樣:

for(View v : parent.children()) 
{ 
    // only checking ViewGroups (layout) obviously you can change 
    // this to suit your needs 
    if(!(v instanceof ViewGroup)) 
     continue; 

    if(v.getHitRect().contains(x, y)) 
     return v; 
} 

這只是僞代碼,需要根據您的使用情況進行調整(即爲嵌套控件添加遞歸)。

希望有所幫助。

+0

毆打拳頭。 :)爲你+1。 – kcoppock

0

我會建議使用TableLayout。由於它是由行和列構成的,您可以通過插入/刪除行或列並動態重建整個佈局來動態地重新排列它們。

但是,這可能意味着你不得不以編程方式設置你的佈局,我可以看到你如何從XML佈局來做到這一點。

(以下是僞代碼)

if (dropping button) { 
    calculate new layout based on which row/column button was moved, and where it was dropped; 
    generate new layout (TableLayout --> addRow --> addView); 
    apply it to buttons view (Buttons.setView(TableLayoutView)); 
} 
2

我會建議通過根XML循環並檢查任何包含的ViewGroups的可見座標;這樣的事情,雖然這是未經測試:

ViewGroup root = (ViewGroup)findViewById(R.id.id_of_your_root_viewgroup); 
//get event coordinates as int x, int y 

public ViewGroup findContainingGroup(ViewGroup v, int x, int y) { 
    for (int i = 0; i < v.getChildCount(); i++) { 
     View child = v.getChildAt(i); 
     if(child instanceof ViewGroup) { 
      Rect outRect = new Rect(); 
      child.getDrawingRect(outRect); 
      if(outRect.contains(x, y)) return child; 
     } 
    } 
} 

ViewGroup parent = findContainingGroup(root, x, y);