Android类参考---Fragment(二)

回退堆栈

在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 simple 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.simple_fragment, newFragment);
ft
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft
.addToBackStack(null);
ft
.commit();
}

每次调用上面这个方法之后,就会在堆栈上增加一个新的实体,并且按下回退键时,会把它从堆栈中弹出,并给用户返回之前的Activity状态。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值