FragmentTransaction中先加入一个Fragment,这个Fragment就是当前要显示的Fragment,
当通过事件触发显示第二个Fragment时,在加入第二个Fragment并调用fragmentTransaction.addToBackStack(null);
在onBackPressed方法中调用mFragmentManager.popBackStack();回到第一个Fragment
package com.example.fragmentdemo; import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; public class MainActivity extends Activity {
private FragmentManager mFragmentManager;
private Fragment1 fragment1;
private Fragment2 fragment2;
private Button button1;
private FragmentTransaction fragmentTransaction; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//新建两个Fragment
fragment1 = new Fragment1();
fragment2 = new Fragment2();
mFragmentManager = getFragmentManager();
//Fragment事务
fragmentTransaction = mFragmentManager.beginTransaction();
//增加执行的动画效果 动画不能用我们的Tween动画,后面会有代码
fragmentTransaction.setCustomAnimations(R.anim.animation_view, R.anim.animation_view_exit);
//加入1个Fragment
fragmentTransaction.add(R.id.myFrameLayout, fragment1);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.commit();
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
fragmentTransaction = mFragmentManager.beginTransaction();
//执行动画,显示fragment2
fragmentTransaction.setCustomAnimations(R.anim.animation_view, R.anim.animation_view_exit);
if (fragment2.isAdded()) {
fragmentTransaction.commit();
}else{
fragmentTransaction.add(R.id.myFrameLayout, fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
}); } @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} @Override
protected void onResume() { super.onResume();
} @Override
public void onBackPressed() {
super.onBackPressed();
mFragmentManager.popBackStack(); } }