在Android中以编程方式合并xml布局

Lui*_*rzi 2 xml android android-layout android-inflate

我已经在Android(树视图)中以编程方式构建了一个布局,现在我想在构建视图中添加一个topbar(topbar.xml).

所以我需要的不是:

setContentView(scroll)
Run Code Online (Sandbox Code Playgroud)

就像是:

inflateInMyViewCalledScroll(topbar.xml)
setContentView(scroll)
Run Code Online (Sandbox Code Playgroud)

谢谢你的建议

Com*_*are 6

充气topbar.xml使用LayoutInflater,将结果放入scroll:

getLayoutInflater().inflate(R.layout.topbar, scroll);
Run Code Online (Sandbox Code Playgroud)


Mat*_*att 5

ScrollView 只能有一个直系子元素。

所以你必须做这样的事情:

<ScrollView>
    <LinearLayout android:id="@+id/foo" android:orientation="vertical">
        <!--  youll add topbar here, programmatically -->
        <other things/>
    </LinearLayout/>
</ScrollView>
Run Code Online (Sandbox Code Playgroud)

然后在运行时,你会膨胀顶栏

View topbar = getLayoutInflater().inflate(R.layout.topbar, null);
Run Code Online (Sandbox Code Playgroud)

并将其添加为第一个索引 foo

foo.addView(topbar, 0);
Run Code Online (Sandbox Code Playgroud)