如何切換標籤內的片段?切換標籤內的片段
我的應用程序包含三個片段,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中只包含一個id 'fragment_container' 一個的LinearLayout用於選項卡AFragment和BFragment。現在我想要以這種方式單擊AFragment中的按鈕將整個AFragment切換到CFragment。我怎樣才能做到這一點?謝謝。
(編輯)我做了以下,但我的應用程序崩潰的開始。我做錯了什麼?
我說我MainActivity.java以下,就在動作條序列如下:
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();
}
});
不相關,但尊重java編碼約定。變量以小寫字母開頭。你的代碼會更容易閱讀。 – Snicolas
謝謝,會做。抱歉。 – Mnemone