【问题标题】: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

【问题讨论】:

    标签: android view android-linearlayout


    【解决方案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);
    

    【讨论】:

    • 谢谢,这正是我所需要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 2011-06-15
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    相关资源
    最近更新 更多