【问题标题】:getActionBar() is always returning nullgetActionBar() 总是返回 null
【发布时间】:2023-03-18 16:24:01
【问题描述】:

我在 Stackoverflow 中浏览过很多类似的帖子,但似乎没有任何问题可以解决我的问题。

我正在尝试获取ActionBar 并调用setDisplayHomeAsUpEnabled(true)

我可以看到黑色的 ActionBar(因为主题是黑色背景),其中 Activity 名称显示为标题。但在我的活动代码中,如果我尝试执行 getActionBar(),它总是返回 null。

我尝试了onResume()onCreate() 中的代码(在扩展布局之后)。它在任何地方都返回 null。我有什么遗漏吗?

AndroidManifest.xml

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".ActivityMain"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

这是我的样式定义。我正在使用Theme.AppCompat.Light.DarkActionBar 主题

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
</style>

另外,我正在使用以下依赖项:

    compile 'com.android.support:support-v4:22.1.0'
    compile 'com.android.support:appcompat-v7:22.2.0'

我的活动类定义是:

MainActivity extends AppCompatActivity

【问题讨论】:

  • 尝试 getSupportActionBar() 而不是 getActionBar()
  • 您是否尝试过使用 getSupportActionBar()。最新的 appcompat-v7 好像禁用了系统栏

标签: android android-layout android-actionbar


【解决方案1】:

尝试使用 getSupportActionBar()。最新的 appcompat-v7 好像禁用了系统栏。

【讨论】:

    【解决方案2】:

    如果你的类定义是MainActivity extends AppCompatActivity,你应该尝试使用getSupportActionBar()

    如果你的类定义是MainActivity extends Activity,你可以尝试使用getActionBar()(这个调用需要API 11)

    【讨论】:

    • 感谢您的宝贵时间。我正在使用 AppCompatActivity。
    猜你喜欢
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多