2014-08-29 23 views

回答

2

嘗試與該代碼,第一個函數開始迭代,第二(第一被叫)穿行於景三和查找按鈕

public ArrayList<Button> getButtons() { 
    ArrayList<Button> buttons = new ArrayList<Button>(); 
    ViewGroup viewGroup = (ViewGroup) getWindow().getDecorView(); 
    findButtons(viewGroup, buttons); 
    return buttons; 
} 

private static void findButtons(ViewGroup viewGroup,ArrayList<Button> buttons) { 
    for (int i = 0, N = viewGroup.getChildCount(); i < N; i++) { 
     View child = viewGroup.getChildAt(i); 
     if (child instanceof ViewGroup) { 
      findButtons((ViewGroup) child, buttons); 
     } else if (child instanceof Button) { 
      buttons.add((Button) child); 
     } 
    } 
} 

希望能夠幫助所有可能的情況下!

+0

你能幫我解決這個問題嗎 – 2014-08-30 07:16:27

1

在這種情況下,ll是一個LinearLayout,並且此搜索僅在此一個佈局中,並且不會遞歸搜索整個視圖樹。像這樣的東西可能有效。沒有測試。

Vector<Button> buttons = new Vector<Button>(); 

for (int i=0; i < ll.getChildCount(); i++){ 
    View v = ll.getChildAt(i); 
    if (v instanceof Button) { 
     buttons.add(v); 
    } 
} 

Button lastButton = buttons.lastElement(); 

我不得不說這聽起來像是你可能以錯誤的方式接近問題。這聽起來像一個非常奇怪的方法。出於好奇,你想達到什麼目的?