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

前端 未结 14 2086
醉酒成梦
醉酒成梦 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 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.

提交回复
热议问题