而不是在xml中爲id加前綴,是否可以在代碼中指定特定的佈局?例如,如果我有3個佈局,每個佈局都帶有一個ID爲「btn」的按鈕。是否可以指定哪個佈局來查找ViewById(R.id.btn)?findViewById在特定的佈局?
3
A
回答
2
基本上下文通過setContentView(R.lyaout.my_layout)
定義。如果你使用LayoutInflater.inflate()
膨脹另一個佈局,你會得到一個佈局對象,我們稱它爲buttonLayout
。您現在可以在this.findViewById(R.id.button)
和buttonLayout.findViewById(R.id.button)
之間有所不同,兩者都會爲您提供不同的按鈕引用。
3
findViewById
是View
類的一種方法。您可以指定視圖應該如何搜索的位置
final View container = new View(context);
container.findViewById(R.id.btn);
+0
它也是一個Activity類的方法 – WarrenFaith
0
如果你的內容視圖是一個複雜的層次結構與ID btn
多個視圖,您需要導航到層次的子樹,並從那裏尋找。假設您有三個LinearLayout
視圖,每個視圖中都有一個btn
視圖。如果你可以先選擇正確的LinearLayout
(通過ID,標籤,位置,或其他方式),然後你可以找到正確的btn
視圖。如果相關LinearLayout
有branch1
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);
}
}
相關問題
- 1. FindViewById在不同的佈局?
- 2. Android的findViewById爲父佈局
- 3. findViewById:引用到佈局
- 4. findViewById從膨脹佈局中返回空
- 5. findViewById返回null從佈局查看
- 6. 使用嵌套佈局定義特定的xml佈局
- 7. Android佈局如何設置特定的固定佈局高度
- 8. 特定佈局建議
- 9. Xamarin.Forms佈局如何轉換爲平臺特定的佈局?
- 10. Android - findViewById方法在片段中查找自定義佈局中的項目
- 11. Android佈局設計特定自定義
- 12. 使用模型的特定佈局
- 13. 針對特定任務的Java佈局
- 14. 表格中的特定行佈局
- 15. 特定網站的CSS佈局
- 16. 啓用特定佈局的滾動
- 17. 創建特定的佈局 - Android電子
- 18. Zend針對特定操作的佈局
- 19. 隱藏特定時間的佈局
- 20. Zend_Navigation和模塊特定的佈局
- 21. setcontentview和findViewById無法在佈局中找到xml和ID
- 22. 如果mapview包含在父佈局中,findViewById將返回null null
- 23. findViewById()在嵌套佈局中找不到id?
- 24. 使特定的Rails視圖使用特定的佈局
- 25. FindViewById和針對不同屏幕密度的多種佈局(Android)
- 26. 針對特定動作使用佈局
- 27. UICollectionView自定義佈局斯威夫特
- 28. 爲特定瀏覽器創建佈局
- 29. 如何在渲染特定視圖時插入佈局伏特?
- 30. 我們如何強制Android系統從特定的佈局文件夾中取得特定的佈局
它會搜索該ID在您通過膨脹的一個inflate或setcontent查看 – Raykud