findViewById()对于夸大的布局返回null

问题描述 投票:1回答:2

我有一个Activity及其布局。现在,我需要从另一个布局LinearLayout中添加一个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。有什么解决办法吗?

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

android android-linearlayout
2个回答
0
投票

说明

当您inflate布局时,该布局尚未出现在UI中,这意味着用户将无法看到它,直到添加了它。为此,您必须持有一个ViewGroupLinearLayoutRelativeLayout等)并将其加成后的View。添加它们后,您可以像使用其他任何视图一样使用它们,包括findViewById方法,添加侦听器,更改属性等

代码

//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为LinearLayoutcontainer
  • other.xml是您项目中的布局文件
  • other.xml包含ID为TextViewexampleTextView

0
投票

尝试使用

 layoutObject.findViewById();
© www.soinside.com 2019 - 2024. All rights reserved.