Android Fragmentation

https://www.jianshu.com/p/d9143a92ad94

 

 

一.Fragment 使用异常

1>.getActivity空指针

protected Activity mActivity; @Override public void onAttach(Activity activity) { super.onAttach(activity); this.mActivity = activity; } /** * 如果你用了support 23的库,上面的方法会提示过时,有强迫症的小伙伴,可以用下面的方法代替 */ @Override public void onAttach(Context context) { super.onAttach(context); this.mActivity = (Activity)context; }

 

2>异常:Can not perform this action after onSaveInstanceState

 

利用onActivityForResult()/onNewIntent(),可以做到事务的完整性,不会丢失事务

// ReceiverActivity 或 其子Fragment: void start(){ startActivityForResult(new Intent(this, SenderActivity.class), 100); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 100 && resultCode == 100) { // 执行Fragment事务 } } // SenderActivity 或 其子Fragment: void do() { // 操作ReceiverActivity(或其子Fragment)执行事务 setResult(100); finish(); }

 

3>.Fragment重叠异常-----正确使用hide、show的姿势

@Override protected void onCreate(@Nullable Bundle savedInstanceState) { // 在页面重启时,Fragment会被保存恢复,而此时再加载Fragment会重复加载,导致重叠 ; if(saveInstanceState == null){ // 或者 if(findFragmentByTag(mFragmentTag) == null) // 正常情况下去 加载根Fragment } }

 

 

 

 

 

你可能感兴趣的:(学习ing)