2012-06-18 28 views
3

而不是在xml中爲id加前綴,是否可以在代碼中指定特定的佈局?例如,如果我有3個佈局,每個佈局都帶有一個ID爲「btn」的按鈕。是否可以指定哪個佈局來查找ViewById(R.id.btn)?findViewById在特定的佈局?

+0

它會搜索該ID在您通過膨脹的一個inflate或setcontent查看 – Raykud

回答

2

基本上下文通過setContentView(R.lyaout.my_layout)定義。如果你使用LayoutInflater.inflate()膨脹另一個佈局,你會得到一個佈局對象,我們稱它爲buttonLayout。您現在可以在this.findViewById(R.id.button)buttonLayout.findViewById(R.id.button)之間有所不同,兩者都會爲您提供不同的按鈕引用。

3

findViewByIdView類的一種方法。您可以指定視圖應該如何搜索的位置

final View container = new View(context); 
container.findViewById(R.id.btn); 
+0

它也是一個Activity類的方法 – WarrenFaith

0

如果你的內容視圖是一個複雜的層次結構與ID btn多個視圖,您需要導航到層次的子樹,並從那裏尋找。假設您有三個LinearLayout視圖,每個視圖中都有一個btn視圖。如果你可以先選擇正確的LinearLayout(通過ID,標籤,位置,或其他方式),然後你可以找到正確的btn視圖。如果相關LinearLayoutbranch1 ID,例如:

View parent = findViewById(R.id.branch1); // Activity method 
View btn = parent.findViewById(R.id.btn); // View method 
0

,如果你有不同的Viewgroups裏面你btns,這是可能的,但需要給ViewGroups一個不同的名字! Easyiest將爲此目的定義按鈕的佈局自己的XML內(即button_layout.xml) 你的活動中,你可以這樣做:

public MyActivity extends Activity{ 

    Button btn1, btn2, btn3; 

    public void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 
    LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); 

    LinearLayout ll = new LinearLayout(this); 
    setContentView(ll); 

    btn1 = (Button)inflater.inflate(R.layout.button_layout, ll); 
    btn2 = (Button)inflater.inflate(R.layout.button_layout, ll); 
    btn3 = (Button)inflater.inflate(R.layout.button_layout, ll); 

    } 
}