Fragment 一些事

一、 Fragment为什么要用newInstance来初始化:

利用Android studio新建fragment的时候,利用谷歌提供的模版,可以看到,新建一个fragment时,fragment的初始化,采用的是静态工厂的形式,具体代码如下:

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link Blank.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link BlankFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BlankFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public BlankFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment AccountMyProfileFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BlankFragment newInstance(String param1, String param2) {
        BlankFragment fragment = new BlankFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_account_my_profile, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * 

* See the Android Training lesson Communicating with Other Fragments for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } }

默认的fragment是利用静态工厂的方式对fragment进行初始化的,传入两个参数,但是会有部分人会采用new BlankFragment()的形式对fragment进行初始化。

那么,采用new BlankFragment()和Fragment.newInstance()的方式具体有什么不同?
activity在默认情况下,切换横竖屏,activity会销毁重建,依附于上面的fragment也会销毁重建,根据这个思路,我们找到fragment重建时调用的代码:

public static Fragment instantiate(Context context, String fname, @Nullable 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);
            if (!Fragment.class.isAssignableFrom(clazz)) {
                throw new InstantiationException("Trying to instantiate a class " + fname
                        + " that is not a Fragment", new ClassCastException());
            }
            sClassMap.put(fname, clazz);
        }
        Fragment f = (Fragment) clazz.getConstructor().newInstance();
        if (args != null) {
            args.setClassLoader(f.getClass().getClassLoader());
            f.setArguments(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);
    } catch (NoSuchMethodException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": could not find Fragment constructor", e);
    } catch (InvocationTargetException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": calling Fragment constructor caused an exception", e);
    }
}

通过以上代码,我们可以看到,fragment 是通过反射进行重建的,而且只调用了无参构造的方法,这也是有部分人通过 new Fragment() 的方式构建 fragment 时,遇到屏幕切换时,fragment 会报空指针异常的原因!注意看代码中f.setArguments(args);
也就是说,fragment 在初始化之后会把参数保存在 arguments 中,当 fragment 再次重建的时候,它会检查 arguments 中是否有参数存在,如果有,则拿出来再用,所以我们再 onCreate() 方法里面才可以拿到之前设置的参数,但是,fragment 在重建的时候不会调用有参构造,所以通过 new Fragment() 的方法来初始化,fragment 重建时,我们设置的参数就没有了。

二、Fragment 与 Activity 之间的信息传递

1、定义接口

为了实现 Fragment 和与之关联的 Activity 之间的信息传递,我们可以在 Fragment 中定义一个接口,然后在 Activity 中实现这个接口。这个 Fragment 会在 onAttach() 方法中捕捉到 Activity 中实现的这个接口,然后通过调用接口中的方法实现与Activity的交流。

public class BlankFragment extends Fragment {
   ……………………
    private OnFragmentInteractionListener mListener;
   ……………………
    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * 

* See the Android Training lesson Communicating with Other Fragments for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } }

注意这个 Fragment 有一个成员变量 mListener , 现在 Fragment 可以通过调用 mListener 的 onFragmentInteraction() 方法来向 Activity 传递信息。当然,如果接口中有其他方法,也可以调用其他方法。
例如: 当用户点击按钮时, Fragment 中的 onButtonPressed(Uri uri) 方法将会执行,然后在这个方法中调用 onFragmentInteraction() 就可以把信息传递给 Activity。

2、在Activity中实现接口

为了接受 Fragment 中传递过来的信息,Activity 必需实现 OnFragmentInteractionListener 接口,在这里接口中只有一个方法 onFragmentInteraction(Uri) 方法,我们将其实现打印一个土司 (当然我们可以给 OnFragmentInteractionListener 定义多个方法并将其实现)。

public class MainActivity extends AppCompatActivity implements BlankFragment.OnFragmentInteractionListener {

    @BindView(R.id.navigation)
    BottomNavigationView navigation;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_account:
                    replaceFragment(BlankFragment.newInstance(null));
                    return true;
                    default:
            }
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        navigation.setSelectedItemId(navigation.getMenu().getItem(0).getItemId());
    }

    private void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.frag_main, fragment);
        fragmentTransaction.commit();
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

}

三、 Fragment中调用getActivity()时,报空指针异常:

一般的,我们在代码中请求网络数据后,由于是在子线程中得到的结果,更新UI界面时,要在UI线程中进行,如果是在fragment中,则需要执行以下代码:

// 在UI线程中展示吐司
private void showToast(String text) {
    getActivity().runOnUiThread(() ->
            Toast.makeText(getActivity(),text,Toast.LENGTH_SHORT).show()
    );
}

乍一看,代码貌似没什么问题,运行起来也能正常显示,但是这样写,在系统可用内存较低时,会频繁触发crash(尤其在低内存手机上经常遇到),此时,再执行这样的代码,就会报空指针异常了,下面来分析具体原因:

首先,我们来看一下fragment的声明周期:

fragment生命周期

重点关注onAttach()方法和onDetach():

当执行onAttach()时,Fragment已实现与Activity的绑定,在此方法之后调用getActivity()会得到与次Fragment绑定的activity对象;当可用内存过低时,系统会回收Fragment所依附的activity,ye'jiu'sh的onDetach()时,Fragment已实现与Activity解绑,在此方法之后调用getActivity(),由于Fragment已经与Activity解绑,皮之不存毛将焉附?则系统就会返回空指针了。

ok,搞定了具体原因后,再来分析解决办法就变得容易了,我们可以在onAttach()后的任意一个方法执行时,比如onAttach()时,保存一份activity为全局属性,这样一来,下次调用getActivity()时,直接使用我们保存的全局mActivity来代替即可,代码如下:

private Activity mActivity;

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    mActivity = activity;
}

// 在UI线程中展示吐司
private void showToast(String text) {
    mActivity.runOnUiThread(() ->
            Toast.makeText(mAcitivty, text, Toast.LENGTH_SHORT).show()
    );
}

不过,此方法有个小问题:当系统调用onAttach()时,Fragment与Activity已经分离,此时Fragment定然对用户不可见的,既然不可见,还更新界面做什么呢?岂不白白浪费资源嘛?这个问题,我们再第三节中进行分析解决

四、Fragment不调用onResume或者onPause方法:

首先,来看Fragment的源码:

/**
 * Called when the fragment is visible to the user and actively running.
 * This is generally
 * tied to {@link Activity#onResume() Activity.onResume} of the containing
 * Activity's lifecycle.
 */
public void onResume() {
    mCalled = true;
}
/**
 * Called when the Fragment is no longer resumed.  This is generally
 * tied to {@link Activity#onPause() Activity.onPause} of the containing
 * Activity's lifecycle.
 */
public void onPause() {
    mCalled = true;
}

注意看方法上面的注释,调用两个方法,返回的是此Fragment所依附的Activity的声明周期中的onResume()和onPause(),并不是Fragment自身的onResume()和onPause(),那么,如果我们也想实现类似Acitivity的onResume()和onPause(),应该怎么做呢?我们继续翻Fragment的源码,找到这么个方法:

/**
 * Set a hint to the system about whether this fragment's UI is currently visible
 * to the user. This hint defaults to true and is persistent across fragment instance
 * state save and restore.
 *
 * 

An app may set this to false to indicate that the fragment's UI is * scrolled out of visibility or is otherwise not directly visible to the user. * This may be used by the system to prioritize operations such as fragment lifecycle updates * or loader ordering behavior.

* * @param isVisibleToUser true if this fragment's UI is currently visible to the user (default), * false if it is not. */ public void setUserVisibleHint(boolean isVisibleToUser) { if (!mUserVisibleHint && isVisibleToUser && mState < STARTED) { mFragmentManager.performPendingDeferredStart(this); } mUserVisibleHint = isVisibleToUser; mDeferStart = !isVisibleToUser; }

注释中说的很清楚,此方法是告诉系统,当前Fragment是否对用户可见,其中有一个isVisibleToUser参数,我们可以重写这个方法,通过判断isVisibleToUser的值来确定此Fragment是否对用户可见,从而间接实现onResume()和onPause()的功能,具体代码如下:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if(isVisibleToUser){
        //TODO:执行对用户可见时的代码
    }else {
        //TODO:执行对用户可不见时的代码
    }
}

简单来说,就是 Fragment 与 Activity 传递信息,或绑定在同一个 Activity 上的不同 Fragment 传递信息,都需要通过这个 Activity 实现。而这个 Activity 则必需实现 Fragment 中的 OnFragmentInteractionListener 接口。因为信息的传递就是通过这个接口中的方法得意实现的。

你可能感兴趣的:(Fragment 一些事)