ActivityGroup是一個已經被廢棄的類,用于在一個Activity中管理多個子Activity。它現在已經不推薦使用,應該使用Fragment來實現類似的功能。
如果你仍然想了解如何使用ActivityGroup,以下是一個簡單的示例:
public class MyActivityGroup extends ActivityGroup {
private HashMap<String, String> mIdMap = new HashMap<>();
private String mCurrentId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mIdMap.put("FirstActivity", "com.example.FirstActivity");
mIdMap.put("SecondActivity", "com.example.SecondActivity");
// 啟動默認的子Activity
startChildActivity("FirstActivity", new Intent(this, FirstActivity.class));
}
public void startChildActivity(String id, Intent intent) {
Window window = getLocalActivityManager().startActivity(id, intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
mCurrentId = id;
setContentView(window.getDecorView());
}
}
public void switchChildActivity(String id) {
if (mCurrentId.equals(id)) {
return;
}
Intent intent = new Intent(this, Class.forName(mIdMap.get(id)));
startChildActivity(id, intent);
}
}
public class MainActivity extends AppCompatActivity {
private MyActivityGroup mActivityGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mActivityGroup = new MyActivityGroup();
mActivityGroup.onCreate(savedInstanceState);
// 將MyActivityGroup作為子Activity添加到主Activity中
FrameLayout container = findViewById(R.id.container);
container.addView(mActivityGroup.getLocalActivityManager().getActivity("FirstActivity").getDecorView());
}
public void switchToFirstActivity(View view) {
mActivityGroup.switchChildActivity("FirstActivity");
}
public void switchToSecondActivity(View view) {
mActivityGroup.switchChildActivity("SecondActivity");
}
}
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
通過調用MyActivityGroup的startChildActivity()
和switchChildActivity()
方法,你可以在主Activity中切換顯示不同的子Activity。但是請注意,ActivityGroup已經被廢棄,不再推薦使用,建議使用Fragment來管理多個子界面。