如何在标签内切换片段?
我的应用程序包含三个片段,AFragment,BFragment和CFragment。反过来,这些片段对应于它们自己的布局文件:AFragment包含一个Button,而BFragment和CFragment都有TextView。有一个名为activity_main的第四个布局文件。
现在,我有四个类,MainActivity,AFragment,BFragment和CFragment。 AFragment,BFragment,CFragment类只有典型的每个包含OnCreateView。
MainActivity包含:
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);
}
}
如您所见,activity_main.xml只包含一个LinearLayout,其ID为'fragment_container',用于选项卡AFragment和BFragment。现在我希望它能以这样的方式点击AFragment中的按钮将整个AFragment切换到CFragment。我怎样才能做到这一点?谢谢。
(编辑)我做了以下但是我的应用程序在启动时崩溃了。我做错了什么?
我在MainActivity.java上添加了以下内容,就在ActionBar序列的下方:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appContext = getApplicationContext();
//ActionBar
....
....
....
Button mButton = (Button) 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.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
});
答案 0 :(得分:0)
另外,请注意: