getActionBar() 返回 null

发布于 2024-11-26 21:47:33 字数 767 浏览 1 评论 0原文

我有一个奇怪的问题。 我正在使用 Targetsdk 13 制作一个应用程序。

在我的主要活动的 onCreate 方法中,我调用 getActionBar() 来设置我的操作栏。在 Android 3.2 模拟器上运行时效果很好,但在使用 Android 3.0 和 3.1 时,getActionBar() 方法返回 null。

我觉得这非常奇怪,而且我看不出有任何理由这样做。 这是模拟器的错误还是我需要做些什么才能确保我的应用程序有操作栏?

解决方案: 我想我已经找到了解决这个问题的方法。 我没有使用 setContentView 来设置活动的布局。相反,我使用 fragmentTransaction.add(android.R.id.content, mFragment, mTag) 将片段添加到活动中。 这在 3.2 中工作得很好,但在早期的 honeycomb 版本中,如果您不在 onCreate() 方法中使用 setContentView,则操作栏显然不会设置。 因此,我通过使用 onCreate() 方法中的 setContentView() 方法修复了该问题,并为其提供包含空 FrameLayout 的布局。 我仍然可以像以前一样使用 fragmentTransaction.add(android.R.id.content, mFragment, mTag) 方法。

这不是最漂亮的修复,但它确实有效。

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. This works fine when running on the Android 3.2 emulator, but when using Android 3.0 and 3.1 the getActionBar() method returns null.

I find this extremely odd, and i cannot see any reason why it would do so.
Is this a bug with the emulators or is there something i need to do, in order to ensure that my application has an actionbar?

SOLUTION:
I think I've found a solution for this problem.
I wasn't using the setContentView to set a layout for the activity. Instead I was using fragmentTransaction.add(android.R.id.content, mFragment, mTag) to add a fragment to the activity.
This worked fine in 3.2, but in earlier honeycomb versions the action bar is apparently not set if you don't use the setContentView in the onCreate() method.
So I fixed it by using the setContentView() method in my onCreate() method and just supplying it with a layout that contained an empty FrameLayout.
I can still use the fragmentTransaction.add(android.R.id.content, mFragment, mTag) method the same way as before.

It's not the prettiest fix, but it works.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(25

温暖的光 2024-12-03 21:47:34

使用 getSupportActionBar() 而不是 getActionBar()

Use getSupportActionBar() instead of getActionBar()

清秋悲枫 2024-12-03 21:47:34

就我而言,我的代码中有这个不起作用:

@Override
protected void onCreate(Bundle savedInstanceState) {
    context = getApplicationContext();

    requestWindowFeature(Window.FEATURE_ACTION_BAR);

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
}

然后我按照代码的顺序进行操作:

@Override
protected void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_ACTION_BAR);

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    context = getApplicationContext();
}

它起作用了!

结论: requestWindowFeature 应该是您在 onCreate 方法中调用的第一个函数。

In my case, I had this in my code which did not work:

@Override
protected void onCreate(Bundle savedInstanceState) {
    context = getApplicationContext();

    requestWindowFeature(Window.FEATURE_ACTION_BAR);

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
}

Then I played with the order of the code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_ACTION_BAR);

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    context = getApplicationContext();
}

And it worked!

Conclusion: requestWindowFeature should be the first thing you call in the onCreate method.

冷血 2024-12-03 21:47:34

我有同样的问题。它通过改变styles.xml中的应用程序主题来解决

之前

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

之后

<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">

I had the same issue. It solved by chaning App theme in styles.xml

Before

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

After

<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
空宴 2024-12-03 21:47:34

自从我刚刚遇到这个问题以来,我想添加一件事,如果您尝试在具有父级的 Activity 上使用 getActionBar() ,它将返回 null。我正在尝试重构代码,其中我的 Activity 包含在 ActivityGroup 中,在查看了如何在源代码中创建 ActionBar 的源代码后,我花了好几分钟才“哦,呃”。

One thing I wanted to add since I just ran into this, if you are trying to getActionBar() on an Activity that has a parent, it will return null. I am trying to refactor code where my Activity is contained inside an ActivityGroup, and it took a good few minutes for me to go "oh duh" after looking at the source of how an ActionBar gets created in source.

暮年慕年 2024-12-03 21:47:34

我通过以下更改解决了这个问题:

  1. 更改 minifest android:theme="@android:style/Theme.Holo.Light" >
  2. 添加到类 extends ActionBarActivity
  3. 添加导入到类导入android.support.v7.app.ActionBarActivity

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
〆一缕阳光ご 2024-12-03 21:47:34

要添加到其他答案:

请确保在调用 onCreate() 方法中调用 setActionBar()setSupportActionBar() >getActionBar():

在activity.xml中定义一些Toolbar,然后在onCreate()中:

Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
// Now you can use the get methods:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

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);
戏蝶舞 2024-12-03 21:47:34

就我而言,我只需扩展 AppCompatActivity 而不是 Activity

    supportActionBar?.setDisplayHomeAsUpEnabled(true)

完整活动示例类:

import android.os.Bundle
导入 androidx.appcompat.app.AppCompatActivity

//class LocationFound : Activity() { <-----Does not seem to work with ActionBar in recent versions
class LocationFound : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_location_found)

        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    } }

在版本上

    minSdkVersion 22
    targetSdkVersion 29

In my case I simply had to extend AppCompatActivity instead of Activity

    supportActionBar?.setDisplayHomeAsUpEnabled(true)

Full activity example class:

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

//class LocationFound : Activity() { <-----Does not seem to work with ActionBar in recent versions
class LocationFound : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_location_found)

        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    } }

On Versions

    minSdkVersion 22
    targetSdkVersion 29
半世蒼涼 2024-12-03 21:47:34

我知道我在这个问题上迟到了(而且是 Android 新手),但我发现这里的信息非常有帮助,我认为我应该添加我自己努力的发现,让 ActionBar 按我想要的方式工作,以防像我这样的其他人出现寻求帮助。

我有一个小部件,它是一个没有窗口标题的浮动窗口。我使用样式主题来实现 android:windowIsFloatingandroid:backgroundDimEnabledandroid:windowNoTitle。这个小部件工作得很好,直到我想添加一个按钮来调用具有多个列表片段页面的片段分页器并使用 ActionBar。它会在寻呼机活动上崩溃并出现空指针异常。我将范围缩小到 ActionBar 为空。根据之前对该线程做出贡献的人的发现,我从清单文件中删除了我的主题,并且 ActionBar 工作正常,但现在我的窗口现在不再浮动(它是全屏),并且它有一个我不想要的页面标题。

进一步的研究让我找到了样式和主题 API 培训指南,它引导我到解决方案。我发现我可以将自定义主题添加到清单文件中的各个活动中,而在将其应用到应用程序之前。我的所有窗口现在都具有所需的外观。

I know I am late to the party (and new to Android) on this question but I found the information here very helpful and thought I should add the findings of my own endeavours with getting ActionBar to work as I wanted in case others like me come looking for help.

I have a widget which is a floating window with no window title. I use a style theme to implement android:windowIsFloating, android:backgroundDimEnabled and android:windowNoTitle. The widget worked fine until I wanted to add a button that called a fragment pager with several list fragment pages and used the ActionBar. It would crash on the pager activity with a null pointer exception. I narrowed it down to the ActionBar being null. Following the findings of previous people who contributed to this thread I removed my theme from the manifest file and the ActionBar worked fine but now my window now longer floated (it was fullscreen) and it had a page title I did not want.

Further research took me to the Styles and Themes API Training Guide which led me to a solution. I discovered I could add my custom theme to individual activities in the manifest file whereas before I was applying it to the application. All my windows now have the desired appearance.

软糖 2024-12-03 21:47:34

尝试从 ActionBarActivity 扩展您的 Activity 类。这为我解决了这个问题。执行如下操作:

public class MyActivity extends ActionBarActivity
{
  . . .

在我的例子中,该类仅从 Activity 扩展。

Try extending your Activity class from ActionBarActivity. This solved it for me. Do something like the following:

public class MyActivity extends ActionBarActivity
{
  . . .

In my case the class was extending only from Activity.

浸婚纱 2024-12-03 21:47:34

这也可能对某些人有帮助。

就我而言,这是因为我没有在 menu.xml 中定义上下文

尝试这个:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.android.ActionBarActivity">

而不是这个:

<menu xmlns:android="http://schemas.android.com/apk/res/android">

This may also help some people.

In my case, it was because I had not defined a context in the menu.xml

Try this:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.android.ActionBarActivity">

Instead of this:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
天生の放荡 2024-12-03 21:47:34

只需通过命令单击查看源代码的实现即可:

    private void initWindowDecorActionBar() {
    Window window = getWindow();

    // Initializing the window decor can change window feature flags.
    // Make sure that we have the correct set before performing the test below.
    window.getDecorView();

    if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
        return;
    }

    mActionBar = new WindowDecorActionBar(this);
    mActionBar.setDefaultDisplayHomeAsUpEnabled(mEnableDefaultActionBarUp);

    mWindow.setDefaultIcon(mActivityInfo.getIconResource());
    mWindow.setDefaultLogo(mActivityInfo.getLogoResource());
}

requestWindowFeature(Window.FEATURE_ACTION_BAR);修复了我的问题,因为我看到 requestWindowFeature(Window.FEATURE_ACTION_BAR) 失败;代码是开源的,使用它!

Just check the implementation of source code by command click:

    private void initWindowDecorActionBar() {
    Window window = getWindow();

    // Initializing the window decor can change window feature flags.
    // Make sure that we have the correct set before performing the test below.
    window.getDecorView();

    if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
        return;
    }

    mActionBar = new WindowDecorActionBar(this);
    mActionBar.setDefaultDisplayHomeAsUpEnabled(mEnableDefaultActionBarUp);

    mWindow.setDefaultIcon(mActivityInfo.getIconResource());
    mWindow.setDefaultLogo(mActivityInfo.getLogoResource());
}

requestWindowFeature(Window.FEATURE_ACTION_BAR); Fixed my issue as I saw requestWindowFeature(Window.FEATURE_ACTION_BAR) is failing; code is open source use it !!

简单 2024-12-03 21:47:34

android.support.v7.app.ActionBar actionBar = getSupportActionBar();

工作得很快

android.support.v7.app.ActionBar actionBar = getSupportActionBar();

works pretty quickly

娇纵 2024-12-03 21:47:34

如果从 Fragment 调用此方法,请确保在 onActivityCreated() 中调用此方法

If calling this method from Fragment the make sure to call this in onActivityCreated()

人疚 2024-12-03 21:47:33

可以使用 getSupportActionBar() 代替 getActionBar() 方法。

Can use getSupportActionBar() instead of getActionBar() method.

埖埖迣鎅 2024-12-03 21:47:33

如果您使用的是支持库,

import android.support.v7.app.ActionBarActivity;

public class MainActivity extends ActionBarActivity {

请使用 getSupportActionBar() 而不是 getActionBar()

* 更新:

ActionBarActivity 现在已弃用:

import android.support.v7.app.ActionBarActivity;

我建议使用:

import android.support.v7.app.AppCompatActivity

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
权谋诡计 2024-12-03 21:47:33
  1. 如果您使用android.support.v7.app.AppCompatActivity

    public class HomeActivity extends AppCompatActivity {

那么您应该使用 android.support .v7.app.ActionBar

  ActionBar ab = getSupportActionBar();
  1. 如果您使用android.support.v4.app.FragmentActivity

    public class HomeActivity extends FragmentActivity {

那么您应该使用 android.app .ActionBar

    ActionBar ab = getActionBar();
  1. 如果您使用android.support.v7.app.ActionBarActivity

    public class HomeActivity extends ActionBarActivity {

您应该使用 android.support。 v7.app.ActionBar

   ActionBar ab = getSupportActionBar();
  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();
り繁华旳梦境 2024-12-03 21:47:33

在活动呈现其视图之前,您必须将窗口类型定义为操作栏。

在调用 setContentView() 方法之前使用

requestWindowFeature(Window.FEATURE_ACTION_BAR);

You have to define window type as actionbar before activity render its view.

use

requestWindowFeature(Window.FEATURE_ACTION_BAR);

before calling setContentView() method.

信愁 2024-12-03 21:47:33

我遇到了上述问题,其中 getActionBar() 方法返回 null。我在设置 setContentView() 后调用 getActionBar(),但它仍然返回 null

我通过在 Android Manifest 文件中设置最初丢失的 min-sdk 版本解决了这个问题。

I faced the above issue where getActionBar() method returns null. I was calling the getActionBar() after setting the setContentView() and still its returning a null.

I resolved the issue by setting the min-sdk version in Android Manifest file that was missing initially.
<uses-sdk android:minSdkVersion="11" />

活泼老夫 2024-12-03 21:47:33

ActionBar 需要应用程序或活动的主题才能有应用程序标题。确保您没有将应用程序或活动设置为 Theme.NOTITLE。

<application
    android:name="com.xxx.yyy"
    android:debuggable="false"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/Theme.NoTitle"> // remove this line if you have this in your code


<activity
        android:name="com.xxx.yyy.Activity"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:theme="@style/Theme.NoTitle"  // remove this line if you have in your code
        android:windowSoftInputMode="adjustResize|stateHidden" > 

ActionBar needs application or activity's Theme to have an app title. Make sure you have not styled your application or activity as Theme.NOTITLE.

<application
    android:name="com.xxx.yyy"
    android:debuggable="false"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/Theme.NoTitle"> // remove this line if you have this in your code


<activity
        android:name="com.xxx.yyy.Activity"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:theme="@style/Theme.NoTitle"  // remove this line if you have in your code
        android:windowSoftInputMode="adjustResize|stateHidden" > 
蓝眼睛不忧郁 2024-12-03 21:47:33
import android.support.v7.app.AppCompatActivity;

然后

extends AppCompatActivity

然后使用

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
import android.support.v7.app.AppCompatActivity;

then

extends AppCompatActivity

then use

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
萌辣 2024-12-03 21:47:33

这个答案迟到了,但可能对来自 Google 的任何人都有帮助:您可能很需要

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

styles.xml 中声明。看来 false 可以是默认值。您还需要使用 API 11 或更高版本。

更多详细信息可以在此处文档中找到。具体来说,引用:

提示:如果您有想要删除的自定义活动主题
操作栏,将 android:windowActionBar 样式属性设置为
错误的。但是,如果您使用主题删除操作栏,则
窗口根本不允许操作栏,因此您无法添加它
稍后调用 getActionBar() 将返回 null。

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.

时光无声 2024-12-03 21:47:33

我遇到了同样的问题,解决方案之一是在调用 getActionBar() 之前使用 setContentView()

但还有另一件事解决了这个问题。我将应用程序的主题指定为 @android:style/Theme.Holo.Light

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Holo.Light" >
    ...
</application>

我认为任何包含 true的主题都可以使用。

I had the same problem and one of the solutions was to use setContentView() before calling getActionBar().

But there was another thing that fixed the problem. I specified theme for the application to be @android:style/Theme.Holo.Light.

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Holo.Light" >
    ...
</application>

I think any theme, which has <item name="android:windowActionBar">true</item> in it, can be used.

栀子花开つ 2024-12-03 21:47:33

主要原因是使用不支持 ActionBar 的主题:

在清单文件中,在目标活动或应用程序元素中添加以下内容(如果您想在整个应用程序中统一主题)

支持操作栏的主题示例 "Theme.AppCompat.Light""Theme.Holo.Light" ...

android:theme="@android:style/Theme.Holo.Light"

最好将所有样式放入 styles.xml 中并使用它到处使用"@style/themName" 因此前一个主题将是

android:theme="@style/AppTheme"

,styles.xml 将具有以下内容:

 <style name="AppTheme" parent="Theme.AppCompat.Light">

提示:

  • 有些主题无法在旧 SDK 中使用,例如 "@android: SDK 版本 14 之前不支持 style/Theme.Holo.Light.DarkActionBar"
  • 要让您的应用支持最低特定版本的 SDK,您可以在 < 下添加以下内容/代码>元素:

    
    

  • 要在 AndroidStudio 中指定最低 SDK 版本,您可以通过使用应用程序的 Gradle 文件。

    <前><代码>安卓{
    默认配置{
    minSdkVersion 14
    目标SDK版本21
    }
    }

The main reason for that is using themes that are not supporting ActionBar:

In manifest file add the following either in your target activity or application element (if you want to unify the theme over whole application)

Examples of themes that are supporting action bar "Theme.AppCompat.Light" or "Theme.Holo.Light" ...

android:theme="@android:style/Theme.Holo.Light"

It is better to put all styles in styles.xml and use it everywhere using "@style/themName" so the previous one will be

android:theme="@style/AppTheme"

and styles.xml will have the following:

 <style name="AppTheme" parent="Theme.AppCompat.Light">

Hints:

  • There is some themes that can not be used in old SDKs like "@android:style/Theme.Holo.Light.DarkActionBar" is not supported before SDKs version 14.
  • To allow your app to support minimum specific version of SDK you could add the following under <app> element:

    <uses-sdk android:minSdkVersion="14" />
    
  • To specify min SDK version in AndroidStudio, you could by using app's Gradle file.

    android{
      defaultConfig{
        minSdkVersion 14
        targetSdkVersion 21
      }
    }
    
山人契 2024-12-03 21:47:33

我遇到了这个问题。我正在检查版本号并仅在它大于或等于 Honeycomb 时才启用操作栏,但它返回 null。我找到了原因
根本原因是我在values-v11文件夹下的style.xml中禁用了Holo主题样式。

I ran into this problem . I was checking for version number and enabling the action bar only if it is greater or equal to Honeycomb , but it was returning null. I found the reason
and root cause was that I had disabled the Holo Theme style in style.xml under values-v11 folder.

独自←快乐 2024-12-03 21:47:33

转到 AndroidManifest.xml 并替换

android:theme="@style/AppTheme"

by 

android:theme="@android:style/Theme.Holo.Light.DarkActionBar"

go to the AndroidManifest.xml and replace

android:theme="@style/AppTheme"

by 

android:theme="@android:style/Theme.Holo.Light.DarkActionBar"

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文