Android:如何动态包含 XML 布局? [英] Android: How to dynamically include a XML Layout?

查看:24
本文介绍了Android:如何动态包含 XML 布局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的 UI 分解为几个 XML 布局.第一个是主布局,另一个是内容布局.

I want to decompose my UI into several XML Layouts. The first one would be the main layout, and the other ones would be the content layouts.

我希望能够在运行时动态设置应包含哪个 content_layout,所以我不想在我的XML 文件.

I would like to be able to set which content_layout should be included dynamically at run-time, so I don't want to set a "layout="@+layout/content_layout" in my XML file.

这是我的布局:

main_layout.xml:

main_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="600dp"
    android:layout_height="800dp" >

    <TextView
        android:id="@+id/title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true" />

    <include /> <!-- I WANT TO INCLUDE MY CONTENT HERE -->

    <Button
        android:id="@+id/cancelButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Cancel" />

</RelativeLayout>

content_layout.xml:

content_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/whatever"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent" />

content_layout2.xml:

content_layout2.xml:

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/whatever2"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent" />

我该怎么做?

谢谢!

推荐答案

<RelativeLayout android:id="@+id/rl" ...

在您的代码中:

// get your outer relative layout
RelativeLayout rl = (RelativeLayout) findById(R.id.rl);


// inflate content layout and add it to the relative layout as second child
// add as second child, therefore pass index 1 (0,1,...)

LayoutInflater layoutInflater = (LayoutInflater) 
        this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);    
rl.addView(1, layoutInflater.inflate(R.layout.content_layout, this, false) ); 

这篇关于Android:如何动态包含 XML 布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆