我制作了一个带有两个选项卡的 ActionBar - 一个用于 afragment 和 bfragment。afragment 包含一个按钮。单击 afragment 上的按钮将导致它更改为 cfragment。但是,再次单击选项卡会导致再次加载片段。我能做些什么来防止这种情况,基本上对选项卡说,“当有人点击你时,加载最后一个片段状态(在这种情况下,片段)?
这是我的 MainActivity.java:
public class MainActivity extends Activity {
public static Context appContext;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appContext = getApplicationContext();
//ActionBar
ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab PlayerTab = actionbar.newTab().setText("Fragment A");
ActionBar.Tab StationsTab = actionbar.newTab().setText("Fragment B");
Fragment PlayerFragment = new AFragment();
Fragment StationsFragment = new BFragment();
PlayerTab.setTabListener(new MyTabsListener(PlayerFragment));
StationsTab.setTabListener(new MyTabsListener(StationsFragment));
actionbar.addTab(PlayerTab);
actionbar.addTab(StationsTab);
}
我的 TabListener:
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(MainActivity.appContext, "Reselected!", Toast.LENGTH_LONG).show();
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
}
}
最后,我的 AFragment.java:
public class AFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.afragment, container, false);
Button mButton = (Button) view.findViewById(R.id.button1);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
CFragment fragment = new CFragment();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
});
return view;
}
}
如何以单击第一个选项卡不会导致再次加载片段的方式将 cfragment 保存到选项卡中?谢谢你。