现在做的是一个TabHost+Activity+ActivityGroup实现多层动态activity嵌套的效果。在TabHost的Tab1页设置了一个ActivityGroup,这个ActivityGroup内部可以切换三个Activity,但是现在出了个问题。当我把切换代码放置在ActivityGroup中(即类似Tabhost那种按钮点击切换),一切正常,而当我把切换代码放在ActivityGroup内部的Activity中(举个例子,有三个activity,我在activity1中点击一个按钮,弹出一个有三个选项的选择对话框,选择了对应选项就把这个ActivityGroup的当前activity切换到选择Activty),这种情况下,即使我设置了activity的模式为singletask,它还是会被销毁。我希望能保留这些activity的状态。
切换代码如下:
切换放置在ActivityGroup中:
ImageView btnModule1 = (ImageView) findViewById(R.id.btnModule1); btnModule1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //清空容器内现有内容 container.removeAllViews(); //加载activity container.addView(getLocalActivityManager().startActivity( "Module1", new Intent(ActivityGroup1.this, Tab1Activity.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)) .getDecorView()); } }); // 模块2 ImageView btnModule2 = (ImageView) findViewById(R.id.btnModule2); btnModule2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { container.removeAllViews(); container.addView(getLocalActivityManager().startActivity( "Module2", new Intent(ActivityGroup1.this, Tab2Activity.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)) .getDecorView()); } }); // 模块3 ImageView btnModule3 = (ImageView) findViewById(R.id.btnModule3); btnModule3.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { container.removeAllViews(); container.addView(getLocalActivityManager().startActivity( "Module3", new Intent(ActivityGroup1.this, Tab3Activity.class) .addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY)) .getDecorView()); } });
切换放置在子Activity,子Activity内的切换代码
//切换报表按钮 public void btn_report_click(View view) { AlertDialog.Builder builder = new AlertDialog.Builder(getParent()); builder.setTitle("选择报表"); //设置dialog标题 final String[]items=new String[]{"实时列表","报表1","报表2","报表3"}; builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //调用ActivityGroup的切换报表方法 ((ReportGroup)getParent()).ChangeActivity(which); } }).show(); }
ActivityGroup内的具体实现代码
//切换Activity方法 public void ChangeActivity(int which) { int current=-1; if(this.getCurrentActivity()!=null) { Activity activity=this.getCurrentActivity(); if(activity instanceof RealTimeVehicleListActivity ) current=0; else current=1; } if(which!=current&¤t!=-1) { setActivity(which); } } private void setActivity(int which) { // TODO Auto-generated method stub switch (which) { case 0: container.removeAllViews(); //加载activity container.addView(getLocalActivityManager().startActivity( "Module1", new Intent(ReportGroup.this, RealTimeVehicleListActivity.class)) .getDecorView()); break; default: container.removeAllViews(); //加载activity container.addView(getLocalActivityManager().startActivity( "Module1", new Intent(ReportGroup.this, Tab1Activity.class)) .getDecorView()); break; }
问题终结,实际原因是我在setActivity方法中的getLocalActivityManager().startActivity()使用了同一个IDModule1,改为不同IDjiu好了。