メインアクティビティと 3 つのフラグメント (1、2、3) があります。そして、このすべてのフラグメントは 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();
}
}
}
しかし、戻る矢印をクリックすると、例外が発生しました
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());
}
手伝って頂けますか?エラーはどこにありますか? 私は何を間違っていますか?