展会信息港展会大全

Android类参考---Fragment(二)
来源:互联网   发布日期:2015-09-29 11:03:38   浏览:1963次  

导读:上一篇:http://www.2cto.com/kf/201205/134000.html回退堆栈在Fragment中被编辑的事务能够放在它自己的Activity中回退堆栈内。当用户在该Ac...

上一篇:http://www.2cto.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 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状态。

摘自 FireOfStar的专栏

赞助本站

人工智能实验室

相关热词: android开发 教程

AiLab云推荐
推荐内容
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港