我有一个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>
也不起作用。
当您inflate布局时,该布局尚未出现在UI中,这意味着用户将无法看到它,直到添加了它。为此,您必须持有一个ViewGroup
(LinearLayout
,RelativeLayout
等)并将其加成后的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
}
});
LinearLayout
的container
TextView
的exampleTextView
尝试使用
layoutObject.findViewById();