有些情况下需要把一个Activity分割成几部分,如上半部分绘制图形,下半部分显示图表,这时就需要用到ActivityGroup。
定义一个类继承自ActivityGroup,Java文件如下:
package com.h.callsta; import android.app.ActivityGroup;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout; public class DetailActivity extends ActivityGroup{ private LinearLayout lo1, lo2;
// LocalActivityManager对象
LocalActivityManager lam = getLocalActivityManager(); public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
// 获得LinearLayout对象
lo1 = (LinearLayout) findViewById(R.id.lo1);
lo2 = (LinearLayout) findViewById(R.id.lo2);
start_activity(); } public void start_activity(){ // 加载两个窗口
Window win1 = lam.startActivity("0",
new Intent(DetailActivity.this, DetailChart.class));
View view1 = win1.getDecorView();
lo1.addView(view1);
Window win2 = lam.startActivity("1",
new Intent(DetailActivity.this, DetailList.class));
View view2 = win2.getDecorView();
lo2.addView(view2); } }
在该类对应的XML布局文件中,定义了两个LinearLayout,分别用来显示两个Activity。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <LinearLayout
android:id="@+id/lo1"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" > </LinearLayout> <LinearLayout
android:id="@+id/lo2"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" > </LinearLayout> </LinearLayout>
在Java文件中,通过getLocalActivityManager()获得LocalActivityManager对象,再通过findViewById()方法获得布局文件中的两个LinearLayout。最后,用LocalActivityManager对象的startActivity()方法,分别启动两个Activity--DetailChart(图形)和DetailList(列表),并分别用getDecorView()方法获得View对象,addView()到两个LinearLayout上,这样,就实现了在一个Activity类同时显示两个Activity。