对于膨胀的布局,findViewById()返回null [英] findViewById() returns null for an inflated layout

查看:142
本文介绍了对于膨胀的布局,findViewById()返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Activity及其布局.现在,我需要从另一个布局menu_layout.xml添加一个LinearLayout.

I have an Activity and its layout. Now I need to add a LinearLayout from another layout, menu_layout.xml.

LayoutInflater inflater;
inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.menu_layout, null); 

此后,findViewById()返回null.有什么解决办法吗?

After this, findViewById() returns null. Is there is any solution for that?

注意:我不能将两种XML放在一个地方,并且使用<include>也不起作用.

Note: I can't put both XML in one place, and using <include> also is not working.

推荐答案

说明

膨胀布局时,该布局尚未出现在UI中,这意味着用户将无法看到它,直到添加它为止.为此,您必须持有ViewGroup(LinearLayoutRelativeLayout等),然后将已膨胀的View添加到其中.添加它们后,您可以像使用其他任何视图一样使用它们,包括findViewById方法,添加侦听器,更改属性等

Explanation

When you inflate a layout, the layout is not in the UI yet, meaning the user will not be able to see it until it's been added. To do this, you must get a hold of a ViewGroup (LinearLayout,RelativeLayout,etc) and add the inflated View to it. Once they're added, you can work on them as you would with any other views including the findViewById method, adding listeners, changing properties, etc

//Inside onCreate for example
setContentView(R.layout.main); //Sets the content of your activity
View otherLayout = LayoutInflater.from(this).inflate(R.layout.other,null);

//You can access them here, before adding `otherLayout` to your activity
TextView example = (TextView) otherLayout.findViewById(R.id.exampleTextView);

//This container needs to be inside main.xml
LinearLayout container = (LinearLayout)findViewById(R.id.container);

//Add the inflated view to the container    
container.addView(otherLayout);

//Or access them once they're added
TextView example2 = (TextView) findViewById(R.id.exampleTextView);

//For example, adding a listener to the new layout
otherLayout.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        //Your thing
    }
});

假设

  • main.xml包含ID为container
  • LinearLayout
  • other.xml是项目中的布局文件
  • other.xml包含ID为exampleTextView
  • TextView

    Assuming

    • main.xml contains a LinearLayout with the id container
    • other.xml is a layout file in your project
    • other.xml contains a TextView with the id exampleTextView
    • 这篇关于对于膨胀的布局,findViewById()返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆