我希望我的活动包含2个片段,并使用操作栏上的按钮在它们之间切换.所以这是我的活动的布局:
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
在activity的onCreate()中,我将两个片段添加到容器中…因为我需要在secondFragment之前执行firstFragment,所以我先添加它,然后隐藏secondFragment,这样用户将按正确的顺序看到片段:
if (findViewById(R.id.fragment_container) != null) {
if (savedInstanceState != null) {
return;
}
FirstFragment firstFragment = new FirstFragment();
SecondFragment secondFragment = new SecondFragment();
firstFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment, "FirstFragment")
.add(R.id.fragment_container, secondFragment, "SecondFragment")
.hide(secondFragment)
.commit();
}
当用户触摸操作栏上的按钮时,会执行以下方法,并且应该隐藏一个片段并显示另一个片段,但没有任何反应……
public void changeFragment(int id){
Fragment secondFragment = new SecondFragment();
Fragment firstFragment = new FirstFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
switch (id){
case 1:
//show 2nd
transaction.hide(firstFragment)
.show(secondFragment)
.commit();
break;
case 2:
//show 1st
transaction.hide(secondFragment)
.show(firstFragment)
.commit();
break;
default:
//do nothing
}
}
我在这里缺少的任何暗示?提前致谢