getActionBar().setDisplayHomeAsUpEnabled(true) throws NullPointerException

前端 未结 4 1272
一整个雨季
一整个雨季 2021-01-03 00:36

This question is asked several times in stackoverflow and I have tried all of them. But unfortunately neither is working for me.

I am trying to implement the naviga

相关标签:
4条回答
  • 2021-01-03 00:47

    You are inheriting from ActionBarActivity. Hence, you need to use getSupportActionBar(), not getActionBar(), to get at the appcompat-v7-supplied action bar backport.

    0 讨论(0)
  • 2021-01-03 00:51

    import v7:

     import android.support.v7.app.ActionBar;
    

    then in the onCreate method:

    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    
    0 讨论(0)
  • 2021-01-03 00:52

    Use this..

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    instead of this - getActionBar().setDisplayHomeAsUpEnabled(true);

    it will work perfectly.

    0 讨论(0)
  • 2021-01-03 00:56

    Summay: To make sure you won't get a NullPointerException. You need to:

    1. Import the right library target to you minium SDK version.
    2. Use the right themes, just as the question owner said.

    But in my situation an if statement is necessary to solve my App from crash. By the way, I'm using an AppCompatActivity to hold my view fragment.

    public onCreateView(LayoutInflater inflater, final ViewGroup container,Bundle savedInstanceState){
        View view = inflater.inflate(R.layout.list_fragment, container, false);
        ActionBar actionBar = getActivity().getActionBar();
        if (actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    
    0 讨论(0)
提交回复
热议问题