Android类参考---Fragment(二)
上一篇:http://www.zzzyk.com/kf/201205/134000.html回退堆栈
在Fragment中被编辑的事务能够放在它自己的Activity中回退堆栈内。当用户在该Activity中按下返回按钮时,在回退堆栈中的任何事务在Activity自己被结束之前会被弹出堆栈。
例如,实例化一个带有整数参数的简单的Fragment对象,并且把这个整数显示在它的UI的一个TextView中:
publicstaticclassCountingFragmentextendsFragment{
int mNum;
/**
* Create a new instance of CountingFragment, providing "num"
* as an argument.
*/
staticCountingFragment newInstance(int num){
CountingFragment f =newCountingFragment();
// Supply num input as an argument.
Bundle args =newBundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
/**
* When creating, retrieve this instance's number from its arguments.
*/
@Override
publicvoid onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mNum = getArguments()!=null? getArguments().getInt("num"):1;
}
/**
* The Fragment's UI is just a 易做图 text view showing its
* instance number.
*/
@Override
publicView onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState){
View v = inflater.inflate(R.layout.hello_world, container,false);
View tv = v.findViewById(R.id.text);
((TextView)tv).setText("Fragment #"+ mNum);
tv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));
return v;
}
}
用下面的方法创建一个新的Fragment实例,用它来替换当前被显示的Fragment实例,并把这种改变发布到回退堆栈上:
void addFragmentToStack(){
mStackLevel++;
// Instantiate a new fragment.
Fragment newFragment =CountingFragment.newInstance(mStackLevel);
// Add the fragment to the activity, pushing this transaction
// on to the back stack.
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.易做图_fragment, newFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
每次调用上面这个方法之后,就会在堆栈上增加一个新的实体,并且按下回退键时,会把它从堆栈中弹出,并给用户返回之前的Activity状态。
摘自 FireOfStar的专栏
补充:移动开发 , Android ,