getActionBar() returns null

前端 未结 24 1230
暗喜
暗喜 2020-11-22 13:31

I\'m having an odd problem. I am making an app with targetsdk 13.

In my main activity\'s onCreate method i call getActionBar() to setup my actionbar. T

相关标签:
24条回答
  • 2020-11-22 13:39

    Use getSupportActionBar() instead of getActionBar()

    0 讨论(0)
  • 2020-11-22 13:41

    If you are using the support library

    import android.support.v7.app.ActionBarActivity;
    
    public class MainActivity extends ActionBarActivity {
    

    use getSupportActionBar() instead of getActionBar()

    * Update:

    The class ActionBarActivity now is deprecated:

    import android.support.v7.app.ActionBarActivity;
    

    I recommend to use:

    import android.support.v7.app.AppCompatActivity
    
    0 讨论(0)
  • 2020-11-22 13:42
    1. if you are using android.support.v7.app.AppCompatActivity

      public class HomeActivity extends AppCompatActivity {

    Then you should be using android.support.v7.app.ActionBar

      ActionBar ab = getSupportActionBar();
    
    1. If you are using android.support.v4.app.FragmentActivity

      public class HomeActivity extends FragmentActivity {

    then you should be using android.app.ActionBar

        ActionBar ab = getActionBar();
    
    1. If you are using android.support.v7.app.ActionBarActivity

      public class HomeActivity extends ActionBarActivity {

    you should be using android.support.v7.app.ActionBar

       ActionBar ab = getSupportActionBar();
    
    0 讨论(0)
  • 2020-11-22 13:43

    This answer is late but might be helpful to anyone who arrives from Google: You might well need to declare

    <item name="android:windowActionBar">true</item>
    

    in your styles.xml. It seems false can be the default. You also need to be on API 11 or higher.

    More details can be found in the documentation here. Specifically, quote:

    Tip: If you have a custom activity theme in which you'd like to remove the action bar, set the android:windowActionBar style property to false. However, if you remove the action bar using a theme, then the window will not allow the action bar at all, so you cannot add it later—calling getActionBar() will return null.

    0 讨论(0)
  • 2020-11-22 13:44

    I solve it by this changes:

    1. change in minifest android:theme="@android:style/Theme.Holo.Light" >
    2. add to class extends ActionBarActivity
    3. add import to class import android.support.v7.app.ActionBarActivity
    0 讨论(0)
  • 2020-11-22 13:44

    To add to the other answers:

    Make sure you call setActionBar() or setSupportActionBar() in your onCreate() method before calling the getActionBar():

    Define some Toolbar in your activity.xml, then in the onCreate():

    Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(toolbar);
    // Now you can use the get methods:
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
    0 讨论(0)
提交回复
热议问题