public class MainActivity extends FragmentActivity implements OnClickListener {
private FragmentA A;
private FragmentB B;
private FragmentC C;
private List<Fragment> mList = new ArrayList<Fragment>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btnA).setOnClickListener(this);
findViewById(R.id.btnB).setOnClickListener(this);
findViewById(R.id.btnC).setOnClickListener(this);
A = new FragmentA();
B = new FragmentB();
C = new FragmentC();
FragmentManager manager = this.getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.fl, A, "FragmentA");
transaction.add(R.id.fl, B, "FragmentB");
transaction.add(R.id.fl, C, "FragmentC");
transaction.hide(B).hide(C).commit();
}
public void insertFragment(Fragment fragment) {
if (mList.contains(fragment)) {
mList.remove(fragment);
mList.add(fragment);
} else {
mList.add(fragment);
}
}
@Override
public void onClick(View v) {
FragmentManager manager = this.getSupportFragmentManager();
FragmentTransaction tr = manager.beginTransaction();
switch (v.getId()) {
case R.id.btnA:
insertFragment(A);
tr.hide(B).hide(C).show(A).commit();
break;
case R.id.btnB:
insertFragment(B);
tr.hide(A).hide(C).show(B).commit();
break;
case R.id.btnC:
insertFragment(C);
tr.hide(A).hide(B).show(C).commit();
break;
default:
break;
}
}
@Override
public void onBackPressed() {
Log.i("tag", "size" + mList.size());
if (mList.size() > 1) {
hideCurrentFragment(mList.size() - 1);
mList.remove(mList.size() - 1);// 移除最顶上的
// 将此时集合顶上显示出来
showFragment(mList.size() - 1);
} else {// ==1
finish();
}
}
private void hideCurrentFragment(int i) {
FragmentManager manager = this.getSupportFragmentManager();
FragmentTransaction tr = manager.beginTransaction();
Fragment fragment = mList.get(i);
tr.hide(fragment).commit();
}
private void showFragment(int i) {
FragmentManager manager = this.getSupportFragmentManager();
FragmentTransaction tr = manager.beginTransaction();
Fragment fragment = mList.get(i);
tr.show(fragment).commit();
}
简单实现Fragment回退栈效果
最新推荐文章于 2022-03-09 11:08:11 发布