单一Activity与多个Fragment

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();
          }
    }
    
    原文作者:KuTear
    原文地址: https://www.jianshu.com/p/3ba6ccbe70dd
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞