动作条的对象返回为空 [英] ActionBar object is returned as null

查看:165
本文介绍了动作条的对象返回为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到下面的空动作条的对象,因此一个 NullPointerException异常在执行时, actionBar.setDisplayHomeAsUpEnabled(真)。以下是我的code这是从片段的onResume调用。

I get actionBar object below as null, and hence a NullPointerException when executing actionBar.setDisplayHomeAsUpEnabled(true). Following is my code which is called from onResume of the Fragment.

ActionBar actionBar = getActivity().getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);

Followwing是我申请到活动中的onCreate主题:

Followwing is the theme I apply to the activity in the onCreate:

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

        <item name="actionBarStyle">@style/MyActionBar</item>
        <item name="actionBarTabTextStyle">@style/MyActionBarTabText</item>
        <item name="actionMenuTextColor">@color/green</item>
        <item name="colorPrimary">@color/green</item>
        <item name="colorPrimaryDark">@color/greenD</item>

    </style>

我的应用程序的最低API级别设置为14。 请大家帮我解释为什么是动作条返回的对象为空。

My application has minimum api level set to 14. Please help me, explain why is the ActionBar object returned as null.

编辑:      getActivity()getActionBar(); 返回null片段

推荐答案

您需要使用 getSupportActionBar()当你使用 AppCompatActivity 而不是 getActionBar()

You need to use getSupportActionBar() when you use AppCompatActivity instead of getActionBar().

修改

在使用 AppCompat 主题,你必须使用 AppCompatActivity

When you use AppCompat theme you have to use AppCompatActivity.

例如code如何获得动作条

Example code how to get ActionBar:

Activity activity = getActivity();
if(activity != null && activity instanceof AppCompatActivity) {
   AppCompatAcitivyt appCompatActivity = (AppCompatActivity) activity;
   ActionBar actionBar = appCompatActivity.getSupportActionBar();
   //your code
}

这篇关于动作条的对象返回为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆