getActionBar().setDisplayHomeAsUpEnabled(true); throws NullPointerException on new activity creation (Google - Basic Tutorial)

前端 未结 7 2017
自闭症患者
自闭症患者 2020-12-11 00:53

I am following this tutorial and getting a NullPointerException at the onCreate method of the DisplayMessageActivity at this block of code:

if (Build.VERSION         


        
相关标签:
7条回答
  • 2020-12-11 01:13

    I had the same problem.

    In the activity of the manifest i had declared

    android:theme="@android:style/Theme.Black.NoTitleBar
    

    which caused the error. After removing this line, my actionbar worked fine.

    0 讨论(0)
  • 2020-12-11 01:18

    You must have set some theme with your Activity which is not compatible with the Action bar.

    So just check the theme you are using with in your manifest file and remove it

    or if you have defined custom theme go to your res->values->style.xml and make WindowActionBar to true.

    0 讨论(0)
  • 2020-12-11 01:19

    None of the other answers worked for me, really. I just commented out that whole if and it worked. From the method name (and documentation), you don't need that functionality anyway (unless you want it), so no harm done.

    Relevant documentation excerpt:

    Set whether home should be displayed as an "up" affordance. Set this to true if selecting "home" returns up by a single level in your UI rather than back to the top level or front page.

    To set several display options at once, see the setDisplayOptions methods.

    Parameters

    showHomeAsUp true to show the user that selecting home will return one level up rather than to the top level of the app.

    0 讨论(0)
  • 2020-12-11 01:20

    It shouldn't be necessary but there are some behavior inconsistencies between API versions even after API level 14.

    Behavior:

    Back "<" image is displayed but it doesn't work when pressed. As a good practice I use to implement the switch case in order to handle back event.

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    

    It worked for me.

    0 讨论(0)
  • 2020-12-11 01:22

    You are probably using a Theme that doesn't support ActionBar. Hence getActionBar() method throws NullPointerException.

    Trying using this theme:

    android:theme="@android:style/Theme.Holo.Light"
    
    0 讨论(0)
  • 2020-12-11 01:24

    Try changing getActionBar() to getSupportActionBar() or ((ActionBarActivity)getActivity()).getSupportActionBar().

    0 讨论(0)
提交回复
热议问题