Search code examples
androidandroid-actionbar

getActivity().getActionBar() is giving null on fragment


I have a fragment , where I need to change the title of ActionBar dynamically. But when I am using the following code, it is giving me NullPointerException. Here getActionBar() is returning null,my question is how can I get the reference of ActionBar in Fragment class. Appreciate your help in advance.

Fragment Class code:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

      ActionBar mActionBar = getActivity().getActionBar();
      mActionBar.setTitle("Your new score is :"+ i);
      return rootView;
}

Solution

  • I think the best solution is make a call back from your fragment like below:

    Create a call back

    public interface OnActionBarListener {
            void onChangeActionBarTitle(int score);
        }
    

    and implement it in your activity

    public class YourActivity extends AppCompatActivity
            implements OnActionBarListener {
        @Override
        public void onChangeActionBarTitle(int score) {
           mActionBar.setTitle("Your new score is :"+ score);
        }
    }
    

    and in your fragment

    public class YourFragment extends Fragment {
        OnActionBarListener mListener;
    
     @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            if (context instanceof YourActivity) {
                mListener = (OnActionBarListener) context;
            }
    
        }
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
           if (mListener != null) mListener.onChangeActionBarTitle(i);
           return rootView;
    }
    
    }
    

    Hope this helps !

    UPDATE 1: base on your request, if you want your activity listen every button click on your fragment, try below code in your fragment

    Button mButton1;
    Button mButton2;
    
    mButton1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    changeTitle(your_score);
                }
            });
    mButton2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    changeTitle(your_score);
                }
            });
    
    void changeTitle(int score) {
            if (mListener != null) mListener.onChangeActionBarTitle(i);
        }