我有一个带有两个选项卡(片段)的布局。第一个选项卡是一个简单的 ListFragment。第二个选项卡是扩展SupportMapFragment的片段。当我单击第二个选项卡然后重新单击原始选项卡时,我遇到了重绘问题(请参见屏幕截图)。如果我使用常规片段而不是 SupportMapFragment,则不会发生这种情况。这是包含两个选项卡的父活动的代码:
public class MainActivity extends ActionBarActivity {
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Notice that setContentView() is not used, because we use the root
// android.R.id.content as the container for each fragment
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tab1 = actionBar.newTab()
.setText(R.string.title_routes_list)
.setTag(R.string.title_routes_list)
.setTabListener(new TabListener<RoutesListFragment>(
this, getString(R.string.title_routes_list), RoutesListFragment.class));
actionBar.addTab(tab1);
Tab tab2 = actionBar.newTab()
.setText(R.string.title_routes_map)
.setTag(R.string.title_routes_map)
.setTabListener(new TabListener<RoutesMapFragment>(
this, getString(R.string.title_routes_map), RoutesMapFragment.class));
actionBar.addTab(tab2);
//GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the previously serialized current tab position.
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getSupportActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Serialize the current tab position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getSupportActionBar()
.getSelectedNavigationIndex());
}
private class TabListener<T extends Fragment> implements ActionBar.TabListener {
private final ActionBarActivity mActivity;
private final String mTag;
private final Class<T> mClass;
private Fragment mFragment;
public TabListener(ActionBarActivity activity, String tag, Class<T> clz) {
this(activity, tag, clz, null);
}
public TabListener(ActionBarActivity activity, String tag, Class<T> clz, Bundle args) {
mActivity = activity;
mTag = tag;
mClass = clz;
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Fragment preInitializedFragment = mActivity.getSupportFragmentManager().findFragmentByTag(mTag);
if (preInitializedFragment == null) {
mFragment = Fragment.instantiate(mActivity, mClass.getName(), null);
ft.add(android.R.id.content, mFragment, mTag);
} else {
ft.attach(preInitializedFragment);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Fragment preInitializedFragment = mActivity.getSupportFragmentManager().findFragmentByTag(mTag);
if (preInitializedFragment != null) {
ft.detach(preInitializedFragment);
} else if (mFragment != null) {
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
}