我有主要活动和三个片段(一、二、三)。所有这些片段都扩展了 BaseFragment:
public abstract class BaseFragment extends Fragment {
private Toolbar mToolbar;
private ActionBar mActionBar;
@Override
@CallSuper
public void onAttach(Activity context) {
super.onAttach(context);
mToolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
mActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
//mActionBar.setTitle(setMyTitle());
//Log.i("BaseFragment", "onAttach = "+getBackStackCount());
resetToolbarNavigation(getBackStackCount()!=0);
}
//protected abstract String setMyTitle();
@Override
@CallSuper
public void onDetach() {
super.onDetach();
Log.i("BaseFragment", "onDetach = " + (getBackStackCount() - 1));
resetToolbarNavigation((getBackStackCount() - 1 )!= 0);
}
private int getBackStackCount() {
int b = getActivity().getSupportFragmentManager().getBackStackEntryCount();
Log.i("BaseFragment", "getBackStackCount = "+b);
return b;
}
private void resetToolbarNavigation(boolean backNavigationEnabled) {
mActionBar.setDisplayHomeAsUpEnabled(backNavigationEnabled);
Log.i("BaseFragment", "resetToolbarNavigation");
if (backNavigationEnabled) {
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.i("resetToolbarNavigation", "setNavigationOnClickListener");
getActivity().onBackPressed();
}
});
}
else {
((StartPageActivity) getActivity()).initToolbar();
((StartPageActivity) getActivity()).syncState();
}
}
}
但是当我点击后退箭头时,我得到了 Exeption
09-22 19:28:13.233 5643-5643/com.test.mylist E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.test.exemple.BaseFragment$1.onClick(BaseFragment.java:56)
at android.view.View.performClick(View.java:2485)
at android.view.View$PerformClick.run(View.java:9080)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
onBackPressed 在主要活动中
@Override
public void onBackPressed() {
getSupportFragmentManager().popBackStack();
Log.d("StartPageActivity", "onBackPressed " + getSupportFragmentManager().getBackStackEntryCount());
}
你能帮助我吗?错误在哪里?我究竟做错了什么?