亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Android 中為什么要用Fragment.setArguments來傳遞參數(shù)

Original 2017-01-13 10:53:13 629
abstract:Fragment在Android3.0開始提供,并且在兼容包中也提供了Fragment特性的支持。Fragment的推出讓我們編寫和管理用戶界面更快捷更方便了。但當(dāng)我們實(shí)例化自定義Fragment時(shí),為什么官方推薦Fragment.setArguments(Bundle bundle)這種方式來傳遞參數(shù),而不推薦通過構(gòu)造方法直接來傳遞參數(shù)呢?為了弄清這個(gè)問題,我們可以做一個(gè)測(cè)試,分別測(cè)試下這兩種方

Fragment在Android3.0開始提供,并且在兼容包中也提供了Fragment特性的支持。Fragment的推出讓我們編寫和管理用戶界面更快捷更方便了。

但當(dāng)我們實(shí)例化自定義Fragment時(shí),為什么官方推薦Fragment.setArguments(Bundle bundle)這種方式來傳遞參數(shù),而不推薦通過構(gòu)造方法直接來傳遞參數(shù)呢?為了弄清這個(gè)問題,我們可以做一個(gè)測(cè)試,分別測(cè)試下這兩種方式的不同

首先,我們來測(cè)試下通過構(gòu)造方法傳遞參數(shù)的情況

public class FramentTestActivity extends ActionBarActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState == null) {
      getSupportFragmentManager().beginTransaction()
          .add(R.id.container, new TestFragment("param")).commit();
    }
  }
  public static class TestFragment extends Fragment {
    private String mArg = "non-param";
    public TestFragment() {
      Log.i("INFO", "TestFragment non-parameter constructor");
    }
    public TestFragment(String arg){
      mArg = arg;
      Log.i("INFO", "TestFragment construct with parameter");
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
      View rootView = inflater.inflate(R.layout.fragment_main, container,
          false);
      TextView tv = (TextView) rootView.findViewById(R.id.tv);
      tv.setText(mArg);
      return rootView;
    }
  }
}

   

可以看到我們傳遞過來的數(shù)據(jù)正確的顯示了,現(xiàn)在來考慮一個(gè)問題,如果設(shè)備配置參數(shù)發(fā)生變化,這里以橫豎屏切換來說明問題,顯示如下

發(fā)生了什么問題呢?我們傳遞的參數(shù)哪去了?為什么會(huì)顯示默認(rèn)值?不急著討論這個(gè)問題,接下來我們來看看Fragment.setArguments(Bundle bundle)這種方式的運(yùn)行情況

public class FramentTest2Activity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout. activity_main);
       if (savedInstanceState == null) {
          getSupportFragmentManager().beginTransaction()
                 .add(R.id. container, TestFragment.newInstance("param")).commit();
       }
    }
    public static class TestFragment extends Fragment {
       private static final String ARG = "arg";
       public TestFragment() {
          Log. i("INFO", "TestFragment non-parameter constructor" );
       }
       public static Fragment newInstance(String arg){
          TestFragment fragment = new TestFragment();
          Bundle bundle = new Bundle();
          bundle.putString( ARG, arg);
          fragment.setArguments(bundle);
           return fragment;
       }
       @Override
       public View onCreateView(LayoutInflater inflater, ViewGroup container,
              Bundle savedInstanceState) {
          View rootView = inflater.inflate(R.layout. fragment_main, container,
                 false);
          TextView tv = (TextView) rootView.findViewById(R.id. tv);
          tv.setText(getArguments().getString( ARG));
           return rootView;
       }
    }
}

   

我們?cè)賮砜纯礄M豎屏切換后的運(yùn)行情況

看到了吧,我們傳遞的參數(shù)在橫豎屏切換的情況下完好保存了下來,正確的顯示給用戶
那么這到底是怎么回事呢,我們知道設(shè)備橫豎屏切換的話,當(dāng)前展示給用戶的Activity默認(rèn)情況下會(huì)重新創(chuàng)建并展現(xiàn)給用戶,那依附于Activity的Fragment會(huì)進(jìn)行如何處理呢,我們可以通過源碼來查看

先來看看Activity的onCreate(Bundle saveInstance)方法

protected void onCreate(Bundle savedInstanceState) {
  if (DEBUG_LIFECYCLE ) Slog.v( TAG, "onCreate " + this + ": " + savedInstanceState);
  if (mLastNonConfigurationInstances != null) {
    mAllLoaderManagers = mLastNonConfigurationInstances .loaders ;
  }
  if (mActivityInfo .parentActivityName != null) {
    if (mActionBar == null) {
      mEnableDefaultActionBarUp = true ;
    } else {
      mActionBar .setDefaultDisplayHomeAsUpEnabled( true);
    }
  }
  if (savedInstanceState != null) {
    Parcelable p = savedInstanceState.getParcelable( FRAGMENTS_TAG );
    mFragments .restoreAllState(p, mLastNonConfigurationInstances != null
        ? mLastNonConfigurationInstances .fragments : null);
  }
  mFragments .dispatchCreate();
  getApplication().dispatchActivityCreated( this , savedInstanceState);
  mCalled = true ;
}

   

由于我們的Fragment是由FragmentManager來管理,所以可以跟進(jìn)FragmentManager.restoreAllState()方法,通過對(duì)當(dāng)前活動(dòng)的Fragmnet找到下面的代碼塊

for (int i=0; i<fms.mActive.length; i++) {
      FragmentState fs = fms.mActive[i];
      if (fs != null) {
       Fragment f = fs.instantiate(mActivity, mParent);
        if (DEBUG) Log.v(TAG, "restoreAllState: active #" + i + ": " + f);
        mActive.add(f);
        // Now that the fragment is instantiated (or came from being
        // retained above), clear mInstance in case we end up re-restoring
        // from this FragmentState again.
        fs.mInstance = null;
      } else {
        mActive.add(null);
        if (mAvailIndices == null) {
          mAvailIndices = new ArrayList<Integer>();
        }
        if (DEBUG) Log.v(TAG, "restoreAllState: avail #" + i);
        mAvailIndices.add(i);
      }
}

   

接下來我們可以看看FragmentState.instantitate()方法的實(shí)現(xiàn)

public Fragment instantiate(Activity activity, Fragment parent) {
    if (mInstance != null) {
      return mInstance ;
    }
    if (mArguments != null) {
      mArguments .setClassLoader(activity.getClassLoader());
    }
    mInstance = Fragment.instantiate(activity, mClassName , mArguments );
    if (mSavedFragmentState != null) {
      mSavedFragmentState .setClassLoader(activity.getClassLoader());
      mInstance .mSavedFragmentState = mSavedFragmentState ;
    }
    mInstance .setIndex(mIndex , parent);
    mInstance .mFromLayout = mFromLayout ;
    mInstance .mRestored = true;
    mInstance .mFragmentId = mFragmentId ;
    mInstance .mContainerId = mContainerId ;
    mInstance .mTag = mTag ;
    mInstance .mRetainInstance = mRetainInstance ;
    mInstance .mDetached = mDetached ;
    mInstance .mFragmentManager = activity.mFragments;
    if (FragmentManagerImpl.DEBUG) Log.v(FragmentManagerImpl.TAG,
        "Instantiated fragment " + mInstance );
    return mInstance ;
  }

   

可以看到最終轉(zhuǎn)入到Fragment.instantitate()方法

public static Fragment instantiate(Context context, String fname, Bundle args) {
  try {
    Class<?> clazz = sClassMap .get(fname);
    if (clazz == null) {
      // Class not found in the cache, see if it's real, and try to add it
      clazz = context.getClassLoader().loadClass(fname);
      sClassMap .put(fname, clazz);
    }
    Fragment f = (Fragment)clazz.newInstance();
    if (args != null) {
      args.setClassLoader(f.getClass().getClassLoader());
      f. mArguments = args;
    }
    return f;
  } catch (ClassNotFoundException e) {
    throw new InstantiationException( "Unable to instantiate fragment " + fname
        + ": make sure class name exists, is public, and has an"
        + " empty constructor that is public" , e);
  } catch (java.lang.InstantiationException e) {
    throw new InstantiationException( "Unable to instantiate fragment " + fname
        + ": make sure class name exists, is public, and has an"
        + " empty constructor that is public" , e);
  } catch (IllegalAccessException e) {
    throw new InstantiationException( "Unable to instantiate fragment " + fname
        + ": make sure class name exists, is public, and has an"
        + " empty constructor that is public" , e);
  }

通過此方法可以看到,最終會(huì)通過反射無參構(gòu)造實(shí)例化一個(gè)新的Fragment,并且給mArgments初始化為原先的值,而原來的Fragment實(shí)例的數(shù)據(jù)都丟失了,并重新進(jìn)行了初始化

通過上面的分析,我們可以知道Activity重新創(chuàng)建時(shí),會(huì)重新構(gòu)建它所管理的Fragment,原先的Fragment的字段值將會(huì)全部丟失,但是通過Fragment.setArguments(Bundle bundle)方法設(shè)置的bundle會(huì)保留下來。所以盡量使用Fragment.setArguments(Bundle bundle)方式來傳遞參數(shù)

更多關(guān)于Android 中為什么要用Fragment.setArguments來傳遞參數(shù)請(qǐng)關(guān)注PHP中文網(wǎng)(ipnx.cn)其他文章!

Release Notes

Popular Entries