提供一個簡單Android的一個項目只使用一個Activity初探案例:
1,新建一個項目
修改和添加三個xml文件:main.xml,item1.xml,item2.xml
a) main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <LinearLayout
- android:id="@+id/content"
- android:layout_width="fill_parent"
- android:layout_height="0dp"
- android:layout_weight="1"
- android:gravity="center_vertical|center_horizontal" >
- </LinearLayout>
-
- <Button
- android:id="@+id/button1"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Change" />
-
- </LinearLayout>
b) item1.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
- <TextView
- android:id="@+id/tv1"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:text="1111111111111111111111111111111111" />
- </LinearLayout>
c) item2.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
- <TextView
- android:id="@+id/tv2"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:text="222222222222222222222222222222222222" />
- </LinearLayout>
修改MainActivity代碼:
- package com.bison.xxxxxxxxxxxxx;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.LinearLayout;
-
- public class MainActivity extends Activity implements OnClickListener {
- LinearLayout content;
- Button btn;
- LinearLayout item1, item2;
- boolean isChange = false;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- // 初始化控件
- content = (LinearLayout) this.findViewById(R.id.content);
- btn = (Button) this.findViewById(R.id.button1);
- btn.setOnClickListener(this);
- // 加載item1
- initItem1();
- }
-
- private void initItem1() {
- item1 = (LinearLayout) LinearLayout.inflate(this, R.layout.item1, null);
- content.addView(item1);
- }
-
- private void initItem2() {
- item2 = (LinearLayout) LinearLayout.inflate(this, R.layout.item2, null);
- content.addView(item2);
- }
-
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.button1:
- isChange = !isChange;
- if (isChange) {
- content.removeView(item1);
- // 加載item2
- initItem2();
- } else {
- content.removeView(item2);
- initItem1();
- }
- break;
- }
- }
-
- }
PS:如果多個Activity具有相同的Header和Footer,則可以考慮使用這種方法來寫.