将自定义布局(从文件)添加到另一个布局

Posted

技术标签:

【中文标题】将自定义布局(从文件)添加到另一个布局【英文标题】:Add custom layout (from file) to another layout 【发布时间】:2012-07-23 03:45:39 【问题描述】:

内容视图是一个线性布局。我们称它为 llOne,我们会说它在文件 llOne.xml 中。

我尝试添加的视图也是一个 LinearLayout,但它们位于单独的文件中。我们称它为 llTwo,我们会说它在 llTwo.xml 文件中。

 setContentView(R.layout.llOne);

 LinearLayout llOne = (LinearLayout) findViewById(R.id.llOne);
 LinearLayout llTwo = (LinearLayout) findViewById(R.id.llTwo);

 llOne.addView(llTwo); //NullPointerException

【问题讨论】:

【参考方案1】:

你需要为第二个布局充气,因为setContentView 只会充气你的llOne

LayoutInflater inflater = (LayoutInflater) mContext
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View otherView = inflater.inflate(R.layout.yourSecondLayoutFileName, null);

然后

LinearLayout llTwo = (LinearLayout) otherView .findViewById(R.id.llTwo);
llOne.addView(llTwo);

【讨论】:

谢谢,这正是我所需要的。

以上是关于将自定义布局(从文件)添加到另一个布局的主要内容,如果未能解决你的问题,请参考以下文章