How to fix getActionBar method may produce java.lang.NullPointerException

前端 未结 14 2089
醉酒成梦
醉酒成梦 2020-12-02 18:06

I am using a toolbar as my actionbar in an activity. I am trying to add the method getActionBar().setDisplayHomeAsUpEnabled(true); to the Activity.java file fo

相关标签:
14条回答
  • 2020-12-02 18:51

    I created a generic class such as:

    public final class Cast
    {
        private Cast() {}
    
        /**
         * Helps to eliminate annoying NullPointerException lint warning.
         */
        @android.support.annotation.NonNull
        public static <T> T neverNull(T value)
        {
            return value;
        }
    }
    

    then I can use it for any call with NullPointerException warning for which I am sure that it will never happen, e.g.

    final ActionBar actionBar = Cast.neverNull(getSupportActionBar());
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);
    

    P.S. don't forget to add "com.android.support:support-annotations" to your gradle file.

    0 讨论(0)
  • 2020-12-02 18:54

    Try this :

    private ActionBar getActionBar() {
        return ((AppCompatActivity) getActivity()).getSupportActionBar();
    }
    
    0 讨论(0)
提交回复
热议问题