2013-07-09 28 views
0

我有一个为我的Activity动态创建的布局(不要问我为什么,这不是我的项目,但我被要求编辑一点)。我正在尝试添加另一个布局,排序状态栏。我对第二个布局IM添加XML布局,这是代码的样子:Android:findViewById返回null

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里面的东西NullPointerException异常。我试图清理项目,但没有帮助。感谢您的任何建议。

回答

2

要设置setContentView()basicLayout

所以你layout永远不会初始化,您buttonslayoutsnull

尝试setContentView(R.layout.XML_LAYOUT_CONTAINING_YOUR_BUTTON);

编辑 使用吹气布局

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); 
+0

但是当我以后添加视图到basicLayout时不会出现这种反弹?像basicLayout.addView(一些视图)? –

+0

@Tomáš'GunsBlazing'Frček请检查编辑答案 –

+0

这样做,非常感谢! :) –

0

如果按钮位于logo_layout中,则需要在该特定布局内进行搜索。

Button back = (Button) logo_layout.findViewById(R.id.button_back); 
+0

我试过,但比我得到一个NullPointerException异常,因为logo_layout也是空的 –