2013-01-07 18 views
3

我有一個複雜的佈局,我向此視圖的SwitchLayout添加了一個標記。通過編號查找父視圖

這個視圖裏面有一個ImageButton。 這裏是一個小地圖按鈕:

的LinearLayout - > SwitchLayout - > RelativeLayout的 - > RelativeLayout的 - >的ImageButton

在某一點上我想連接到SwitchLayout的標籤,但我已經是對ImageButton的引用。

我試圖尋找一個ID,但似乎Android是隻向下搜索,所以

imageButton.findViewById(R.id.switchLayout); 

不起作用。

它也看起來像我不能直接從ImageButton獲得分配標籤。

此代碼:

imageButton.getTag() 

回報null

只有一個解決辦法,我發現在這裏,但它是醜陋:

ViewSwitcher viewSwitcher = (ViewSwitcher)imageButton.getParent().getParent().getParent(); 
viewSwitcher.getTag(); 

我想提出的耦合爲一週儘可能,所以我想知道是否有方法將標籤分配給viewSwitcher及其所有的孩子,

或者在父視圖中找到ViewById。

回答

11

爲什麼不只是保持開關佈局的參考?

// In activity 
switchLayout = findViewById(R.id.switchLayout); 
imageButton = findViewById(R.id.imageButton); 

如果你的方法還是在活動中,您可以直接訪問switchLayout,如果沒有,你可以設置switchLayout到ImageButton的標籤,後來讀它,

imageButton.setTag(switchLayout); 

,或者如果你真的需要做這個,你可以遞歸地做,

public ViewParent findParentRecursively(View view, int targetId) { 
    if (view.getId() == targetId) { 
     return (ViewParent)view; 
    } 
    View parent = (View) view.getParent(); 
    if (parent == null) { 
     return null; 
    } 
    return findParentRecursively(parent, targetId); 
} 
+0

就是這個!謝謝 :) –

0

android中的所有視圖(控件)都是View類型,因此您可以使用getId()來查找id。 您可以使用下面的代碼片段

int parentId = ((View) arg0.getParent()).getId(); 
+0

謝謝你的回答。什麼是arg0? –

+0

arg0是你當前的視圖 –

+0

你的意思是imageButton?那麼這段代碼會給我RelativeLayout的id,這不是我正在尋找的。 –

1

聲明和定義的swtichlayout參考,並直接將標籤。爲什麼你要使用imagebutton獲得switchlayout的標籤。

+0

我有一個分配給switchlayout的類的特定對象。當有人按下我的ImageButton時,我想從該對象調用特定的方法。 –