• Fragment 笔记


      1.getActivity()  为null问题

      在Fragment基类里设置一个Activity mActivity的全局变量,在onAttach(Activity activity)里赋值,使用mActivity代替getActivity(),保证Fragment即使在onDetach后,仍持有Activity的引用

    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.Fragment重叠问题

      (1)findFragmentByTag

        通过findFragmentByTag找到对应的Fragment,并hide()需要隐藏的fragment。

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);
    
        TargetFragment targetFragment;
        HideFragment hideFragment;
    
        if (savedInstanceState != null) {  // “内存重启”时调用
            targetFragment = getSupportFragmentManager().findFragmentByTag(targetFragment.getClass().getName);
            hideFragment = getSupportFragmentManager().findFragmentByTag(hideFragment.getClass().getName);
            // 解决重叠问题
            getFragmentManager().beginTransaction()
                    .show(targetFragment)
                    .hide(hideFragment)
                    .commit();
        }else{  // 正常时
            targetFragment = TargetFragment.newInstance();
            hideFragment = HideFragment.newInstance();
    
            getFragmentManager().beginTransaction()
                    .add(R.id.container, targetFragment, targetFragment.getClass().getName())
                    .add(R.id,container,hideFragment,hideFragment.getClass().getName())
                    .hide(hideFragment)
                    .commit();
        }
    }

      3.remove()方法不是真正的出栈

      popBackStack()系列方法才能真正出栈

      

  • 相关阅读:
    [LeetCode] 26. Remove Duplicates from Sorted Array
    [LeetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal
    [LeetCode] 1248. Count Number of Nice Subarrays
    [LeetCode] 37. Sudoku Solver
    [LeetCode] 36. Valid Sudoku
    [LeetCode] 378. Kth Smallest Element in a Sorted Matrix
    [LeetCode] 547. Friend Circles
    [LeetCode] 733. Flood Fill
    [LeetCode] 695. Max Area of Island
    [LeetCode] 994. Rotting Oranges
  • 原文地址:https://www.cnblogs.com/qianyukun/p/5497556.html
Copyright © 2020-2023  润新知