[英]Android: findViewById returns null
我為我的Activity創建了一個動態創建的布局(不要問我為什么,這不是我的項目,但我被要求編輯一下)。 我正在嘗試添加另一個布局,一種狀態欄。 我添加了第二個布局的XML布局,這就是代碼的樣子:
AbsoluteLayout basicLayout = new AbsoluteLayout(this);
basicLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
setContentView(basicLayout);
LinearLayout logo_layout = (LinearLayout) findViewById(R.id.layout_logo);
Button back = (Button) findViewById(R.id.button_back);
Button options = (Button) findViewById(R.id.button_menu);
但findViewById返回null,每當我嘗試使用LinearLayout內的兩個按鈕執行某些操作時,會導致NullPointerExceptions。 我試圖清理項目,但沒有幫助。 感謝您的任何建議。
您正在將setContentView()
設置為basicLayout
所以你的layout
永遠不會被初始化,你的buttons
和layouts
也是null
嘗試setContentView(R.layout.XML_LAYOUT_CONTAINING_YOUR_BUTTON);
編輯使用布局Inflater
setContentView(basicLayout);
//create a view to inflate the layout from the xml
View view = getLayoutInflater().inflate(R.layout.XML_LAYOUT, basicLayout,false);
//add the view to the basic layout
basicLayout.addView(view);
LinearLayout logo_layout = (LinearLayout) view.findViewById(R.id.layout_logo);
Button back = (Button) view.findViewById(R.id.button_back);
Button options = (Button) view.findViewById(R.id.button_menu);
如果按鈕位於logo_layout中,則需要在該特定布局中進行搜索。
Button back = (Button) logo_layout.findViewById(R.id.button_back);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.