Android: Как динамически включать XML-макет?
Я хочу разложить свой интерфейс на несколько XML-макетов. Первый из них будет основным макетом, а другие - макетами контента.
Я хотел бы иметь возможность установить, какой content_layout должен быть включен динамически во время выполнения, поэтому я не хочу устанавливать "layout="@+layout/content_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:
<?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:
<?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" />
Как я могу это сделать?
Спасибо!
Ответы
Ответ 1
<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) );
Ответ 2
Вы можете попробовать использовать ViewStub и просто изменить, какой макет он будет раздувать программно.
В этом ответе обсуждается использование одного ViewStub.