layout: post
title: 单一Activity与多个Fragment
date: 2015-12-28
categories: blog
tags: [Activity,Fragmnet]
category: Android
description: 很多时候,我只想要一个通用的Activity
来作为大部分Fragment
的依附点,即需要根据startActivity(Intent intent)
的Intent中的参数在CommonActivity
中动态加载不同的Fragment
.
需求
很多时候,我只想要一个通用的Activity
来作为大部分Fragment
的依附点,即需要根据startActivity(Intent intent)
的Intent中的参数在CommonActivity
中动态加载不同的Fragment
.
实现
Fragment
public void jumpToFragment(Class<? extends AbsFragment> fragmentClass, IFragmentParams params) { ActivityParams activityParams = new ActivityParams(fragmentClass, params); Intent intent = new Intent(mActivity, CommonActivity.class); intent.putExtra(CommonActivity.PARAMS, activityParams); startActivity(intent); }
ActivityParams
public class ActivityParams implements Serializable { private Class<? extends AbsFragment> mFragmentClazz; private IFragmentParams mFragmentParams; public ActivityParams(Class<? extends AbsFragment> mFragmentClazz, IFragmentParams mFragmentParams) { this.mFragmentClazz = mFragmentClazz; this.mFragmentParams = mFragmentParams; } public Class<? extends AbsFragment> getFragmentClazz() { return mFragmentClazz; } public IFragmentParams getFragmentParams() { return mFragmentParams; } }
CommonActivity
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mParams = (ActivityParams) getIntent().getSerializableExtra(PARAMS); setContentView(R.layout.fragment_common_layout); try { //通过AbsFragment的静态方法newInstance(IFragmentParams)构造Fragment fragment = (AbsFragment) mParams.getFragmentClazz().getMethod("newInstance", IFragmentParams.class).invoke(null, mParams.getFragmentParams()); if (fragment == null) { L.e(TAG, "Fragment==null"); finish(); return; } getSupportFragmentManager().beginTransaction().add(R.id.klibs_common_fragment,fragment).commit(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } }