Fragment是activity界面的一部分活着一种行为,它不能独立存在,必须嵌入到activity中,而且fragment的生命周期受所在activity的影响。所以fragment之间并不能直接像activity一样跳转。但是我们可以通过回调函数,用activity来控制切换fragment,实现好像fragment之间直接跳转的功能。
做法是在需要跳转的fragment里面实现一个回调接口,然后要求主activity来实现它。当activity通过这个接口接到一个回调,来控制切换的界面。
/**
*
*
* @author hx
* @version 2014-12-01
*
*/
public class DemoFragment extends Fragment{
DemoFragmentSelectedListener mCallback;
//创建回调接口,实现碎片之间的切换
public interface DemoFragmentSelectedListener {
public void onArticleSelected(int position);
}
public void onAttach(Activity activity) {
super.onAttach(activity);
// 确认容器activity已经实现接口
// 回调接口。如果没有,抛出异常
try {
mCallback = (DemoFragmentSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener");
}
}
//实现待跳转界面里面的事件,调用mCallback.onArticleSelected()传递对应的参数。
}
在主activity中实现接口DemoFragmentSelectedListener:
/**
*
*
* @author hx
* @version 2014-12-01
*
*/
public class MainActivity extends Activity
implements DemoFragment.DemoFragmentSelectedListener{
//实现searchFragment的接口,实现界面的跳转
@Override
public void onArticleSelected(int position) {
// TODO Auto-generated method stub
DemoFragment1 newFragment = new DemoFragment1();
Bundle args = new Bundle();
args.putInt("position", position);
newFragment.setArguments(args);//传递参数
android.app.FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, newFragment);//替换跳转
transaction.addToBackStack(null);
transaction.commit();
}
}
在跳转到的DemoFragment1中接收参数。
/**
*
*
* @author hx
* @version 2014-12-01
*
*/
public class DemoFragment1 extends Fragment{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//获取DemoFragment传递过来的参数。
int position = (Integer) getArguments().get("position");
}
}