一遥巴、 Fragment為什么要用newInstance來初始化:
利用Android studio新建fragment的時候姻锁,利用谷歌提供的模版肮雨,可以看到体斩,新建一個fragment時梭稚,fragment的初始化,采用的是靜態(tài)工廠的形式絮吵,具體代碼如下:
/**
* 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.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
默認的fragment是利用靜態(tài)工廠的方式對fragment進行初始化的弧烤,傳入兩個參數(shù),但是會有部分人會采用new BlankFragment()的形式對fragment進行初始化蹬敲。
那么暇昂,采用new BlankFragment()和Fragment.newInstance()的方式具體有什么不同?
activity在默認情況下伴嗡,切換橫豎屏急波,activity會銷毀重建,依附于上面的fragment也會銷毀重建瘪校,根據(jù)這個思路澄暮,我們找到fragment重建時調(diào)用的代碼:
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 是通過反射進行重建的泣懊,而且只調(diào)用了無參構(gòu)造的方法,這也是有部分人通過 new Fragment() 的方式構(gòu)建 fragment 時麻惶,遇到屏幕切換時馍刮,fragment 會報空指針異常的原因!注意看代碼中f.setArguments(args);
也就是說窃蹋,fragment 在初始化之后會把參數(shù)保存在 arguments 中卡啰,當(dāng) fragment 再次重建的時候静稻,它會檢查 arguments 中是否有參數(shù)存在,如果有匈辱,則拿出來再用姊扔,所以我們再 onCreate() 方法里面才可以拿到之前設(shè)置的參數(shù),但是梅誓,fragment 在重建的時候不會調(diào)用有參構(gòu)造恰梢,所以通過 new Fragment() 的方法來初始化,fragment 重建時梗掰,我們設(shè)置的參數(shù)就沒有了嵌言。
二、Fragment 與 Activity 之間的信息傳遞
1及穗、定義接口
為了實現(xiàn) Fragment 和與之關(guān)聯(lián)的 Activity 之間的信息傳遞摧茴,我們可以在 Fragment 中定義一個接口,然后在 Activity 中實現(xiàn)這個接口埂陆。這個 Fragment 會在 onAttach() 方法中捕捉到 Activity 中實現(xiàn)的這個接口苛白,然后通過調(diào)用接口中的方法實現(xiàn)與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.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
注意這個 Fragment 有一個成員變量 mListener 焚虱, 現(xiàn)在 Fragment 可以通過調(diào)用 mListener 的 onFragmentInteraction() 方法來向 Activity 傳遞信息购裙。當(dāng)然,如果接口中有其他方法鹃栽,也可以調(diào)用其他方法躏率。
例如: 當(dāng)用戶點擊按鈕時, Fragment 中的 onButtonPressed(Uri uri) 方法將會執(zhí)行民鼓,然后在這個方法中調(diào)用 onFragmentInteraction() 就可以把信息傳遞給 Activity薇芝。
2、在Activity中實現(xiàn)接口
為了接受 Fragment 中傳遞過來的信息丰嘉,Activity 必需實現(xiàn) OnFragmentInteractionListener 接口夯到,在這里接口中只有一個方法 onFragmentInteraction(Uri) 方法,我們將其實現(xiàn)打印一個土司 (當(dāng)然我們可以給 OnFragmentInteractionListener 定義多個方法并將其實現(xiàn))饮亏。
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中調(diào)用getActivity()時,報空指針異常:
一般的克滴,我們在代碼中請求網(wǎng)絡(luò)數(shù)據(jù)后逼争,由于是在子線程中得到的結(jié)果,更新UI界面時劝赔,要在UI線程中進行誓焦,如果是在fragment中,則需要執(zhí)行以下代碼:
// 在UI線程中展示吐司
private void showToast(String text) {
getActivity().runOnUiThread(() ->
Toast.makeText(getActivity(),text,Toast.LENGTH_SHORT).show()
);
}
乍一看,代碼貌似沒什么問題杂伟,運行起來也能正常顯示移层,但是這樣寫,在系統(tǒng)可用內(nèi)存較低時赫粥,會頻繁觸發(fā)crash(尤其在低內(nèi)存手機上經(jīng)常遇到)观话,此時,再執(zhí)行這樣的代碼越平,就會報空指針異常了频蛔,下面來分析具體原因:
首先,我們來看一下fragment的聲明周期:
重點關(guān)注onAttach()方法和onDetach():
當(dāng)執(zhí)行onAttach()時秦叛,F(xiàn)ragment已實現(xiàn)與Activity的綁定晦溪,在此方法之后調(diào)用getActivity()會得到與次Fragment綁定的activity對象;當(dāng)可用內(nèi)存過低時挣跋,系統(tǒng)會回收Fragment所依附的activity三圆,ye'jiu'sh的onDetach()時,F(xiàn)ragment已實現(xiàn)與Activity解綁避咆,在此方法之后調(diào)用getActivity()舟肉,由于Fragment已經(jīng)與Activity解綁,皮之不存毛將焉附查库?則系統(tǒng)就會返回空指針了路媚。
ok,搞定了具體原因后膨报,再來分析解決辦法就變得容易了磷籍,我們可以在onAttach()后的任意一個方法執(zhí)行時适荣,比如onAttach()時现柠,保存一份activity為全局屬性,這樣一來弛矛,下次調(diào)用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()
);
}
不過丈氓,此方法有個小問題:當(dāng)系統(tǒng)調(diào)用onAttach()時周循,F(xiàn)ragment與Activity已經(jīng)分離,此時Fragment定然對用戶不可見的万俗,既然不可見湾笛,還更新界面做什么呢?豈不白白浪費資源嘛闰歪?這個問題嚎研,我們再第三節(jié)中進行分析解決
四、Fragment不調(diào)用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;
}
注意看方法上面的注釋临扮,調(diào)用兩個方法论矾,返回的是此Fragment所依附的Activity的聲明周期中的onResume()和onPause(),并不是Fragment自身的onResume()和onPause()杆勇,那么贪壳,如果我們也想實現(xiàn)類似Acitivity的onResume()和onPause(),應(yīng)該怎么做呢蚜退?我們繼續(xù)翻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.
*
* <p>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.</p>
*
* @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;
}
注釋中說的很清楚,此方法是告訴系統(tǒng)钻注,當(dāng)前Fragment是否對用戶可見传黄,其中有一個isVisibleToUser參數(shù),我們可以重寫這個方法队寇,通過判斷isVisibleToUser的值來確定此Fragment是否對用戶可見膘掰,從而間接實現(xiàn)onResume()和onPause()的功能,具體代碼如下:
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser){
//TODO:執(zhí)行對用戶可見時的代碼
}else {
//TODO:執(zhí)行對用戶可不見時的代碼
}
}
簡單來說佳遣,就是 Fragment 與 Activity 傳遞信息识埋,或綁定在同一個 Activity 上的不同 Fragment 傳遞信息,都需要通過這個 Activity 實現(xiàn)零渐。而這個 Activity 則必需實現(xiàn) Fragment 中的 OnFragmentInteractionListener 接口窒舟。因為信息的傳遞就是通過這個接口中的方法得意實現(xiàn)的。