【问题标题】:getActionBar().setDisplayHomeAsUpEnabled(true), -> java.lang.NullPointerException Impossible to resolvegetActionBar().setDisplayHomeAsUpEnabled(true), -> java.lang.NullPointerException 无法解决
【发布时间】:2016-01-18 05:50:45
【问题描述】:

我有以下问题:
getActionBar().setDisplayHomeAsUpEnabled(true);

java.lang.NullPointerException

我知道有很多帖子有同样的问题,但我可以解决这个问题。我尝试了所有找到的解决方案,但没有人帮助我,我使用这个 Fragment and Drawer (Android)

这是代码:MainActivity.java

    package com.example.erik.test2;


import android.app.Activity;

import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
    private DrawerLayout mDrawer;
    private Toolbar toolbar;
    private ActionBarDrawerToggle mDrawerToggle;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
       //requestWindowFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        // Set a Toolbar to replace the ActionBar.
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        //setSupportActionBar(toolbar);
       // getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        // Find our drawer view
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        NavigationView nvDrawer = (NavigationView) findViewById(R.id.nvView);
        setupDrawerContent(nvDrawer);

        //---- Open Drawer on clic icon BUT CAUSE NULLPOINT EXEPTION--- //
       //*
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);//*/

        /*
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);//*/
//*
       mDrawerToggle = new ActionBarDrawerToggle(this, mDrawer,  R.drawable.logo_tam, R.string.ouverture, R.string.fermeture) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(R.string.titre);
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(R.string.titre_apres_ouverture);
                invalidateOptionsMenu();
            }
        };
        mDrawer.setDrawerListener(mDrawerToggle); //*

        //-----------------------------------------------------------------------------------------------------------------
/*
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawer, R.drawable.logo_tam, R.string.ouverture, R.string.fermeture ) {
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getActionBar().setTitle("Fermer");
            }
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getActionBar().setTitle("Ouvert");
            }
        };
        // Set the drawer toggle as the DrawerListener
        mDrawer.setDrawerListener(mDrawerToggle);*/

       // getActionBar().setDisplayHomeAsUpEnabled(true);
        //getActionBar().setHomeButtonEnabled(true);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // The action bar home/up action should open or close the drawer.
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawer.openDrawer(GravityCompat.START);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    // Make sure this is the method with just `Bundle` as the signature
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }

    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        selectDrawerItem(menuItem);
                        return true;
                    }
                });
    }

    public void selectDrawerItem(MenuItem menuItem) {
        // Create a new fragment and specify the planet to show based on
        // position
        Fragment fragment = null;
        Class fragmentClass;
        switch(menuItem.getItemId()) {
            case R.id.nav_first_fragment:
                fragmentClass = FirstFragment.class;
                break;
            case R.id.nav_second_fragment:
                fragmentClass = SecondFragment.class;
                break;
            case R.id.nav_third_fragment:
                fragmentClass = ThirdFragment.class;
                break;
            default:
                fragmentClass = FirstFragment.class;
        }

        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Insert the fragment by replacing any existing fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();

        // Highlight the selected item, update the title, and close the drawer
        menuItem.setChecked(true);
        setTitle(menuItem.getTitle());
        mDrawer.closeDrawers();
    }

}

styles.xml 的代码(我已经尝试将主题更改为 Theme.AppCompat.Light 但它不起作用)

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

toolbar.xml的代码

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/Theme.AppCompat.Light"
    android:background="?attr/colorPrimaryDark">
</android.support.v7.widget.Toolbar>

代码activity_main.xml

<!-- This DrawerLayout has two children at the root  -->
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- This LinearLayout represents the contents of the screen  -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- The ActionBar displayed at the top -->
        <!--  <include
              layout="@layout/toolbar"
              android:layout_width="match_parent"
              android:layout_height="wrap_content" /> -->

          <!-- The main content view where fragments are loaded -->
        <FrameLayout
            android:id="@+id/flContent"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>

    <!-- The navigation drawer that comes from the left -->
    <!-- Note that `android:layout_gravity` needs to be set to 'start' -->
    <android.support.design.widget.NavigationView
        android:id="@+id/nvView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@android:color/white"
        app:menu="@menu/drawer_view"
        app:headerLayout="@layout/nav_header"
        />
</android.support.v4.widget.DrawerLayout>

和清单代码

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.erik.test2">

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

    </application>

</manifest>

我在 Theme 中尝试了许多选项,但它在我的 ActivityMain 中不起作用,您可以在评论中看到我尝试的所有测试。

【问题讨论】:

  • 你可以使用getSupportActionBar()
  • 移除评论表单 setSupportActionBar(toolbar);然后使用 getSupportActionBar()
  • 您好,感谢您的快速回答。我已经尝试过,但它不起作用,我把它放在 MainActivity 的 cmets ' getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); ' 和toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  • @RSCP 解决了吗?? stackoverflow.com/questions/26859339/…
  • 使用getSupportActionBar() 而不是getActionBar();

标签: java android xml nullpointerexception


【解决方案1】:

getActionBar().setDisplayHomeAsUpEnabled(true); 给出 NullPointerException 因为在你的 styles.xml 中你已经给了父 Theme.AppCompat.Light.NoActionBar 表示没有 ActionBar。

解决方案:

使用 styles.xml

中给出的以下样式更改您的 style
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

现在在您的 MainAcitivity 中使用此代码

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

如果这对你有帮助,请告诉我。

【讨论】:

    【解决方案2】:

    Bad Approach

    使用弃用代码。避免调用 ActionBarActivity

    建议

    从 22.1.0 版本开始,ActionBarActivity 类已被弃用。 您应该使用 AppCompatActivity。

    你得到了

    getActionBar().setDisplayHomeAsUpEnabled(true); java.lang.NullPointerException

    注释掉这行首先

    <include
              layout="@layout/toolbar"
              android:layout_width="match_parent"
              android:layout_height="wrap_content" />
    

    第二个,您可以使用getSupportActionBar() 代替getActionBar() 并添加null 检查

    if (getSupportActionBar() != null)
    {
       getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    

    您可以更改主题,因为您使用的是NoActionBar

    parent="Theme.AppCompat.Light.NoActionBar"
    

    使用 Toolbar 替换 ActionBar 非常简单 并从确保活动扩展开始 动作栏活动。还要确保此活动的主题是 Theme.AppCompat.NoActionBar 或 Theme.AppCompat.Light.NoActionBar。

    请查看#SO回答What to use instead of getSupportActionBar()

    https://developer.android.com/intl/pt-br/reference/android/support/v7/widget/Toolbar.html

    【讨论】:

    • 您的回答更好,但我认为您还应该在致电getSupportActionBar() 之前添加setSupportActionBar(toolbar)
    【解决方案3】:

    你有两种方法:
    1. 使用getSupportActionBar() 代替getActionBar()
    2. 更改您的活动以扩展ActionBarActivity

    【讨论】:

    • IntelliJ Amiya 和 MHP 非常感谢您,我使用您的答案,现在效果很好:1)我将 MainActivity 替换为“ActionBarActivity” 2)在我替换 getActionBar() 之后 ....通过'如果(getSupportActionBar()!= null)''{''getSupportActionBar().setDisplayHomeAsUpEnabled(true);' 'getSupportActionBar().setHomeButtonEnabled(true);' ' }' 3) 在样式中我使用 juste Theme.AppCompat.Light 4) 我删除 'toolbar = (Toolbar) findViewById(R.id.toolbar);'
    • ActionBarActivity 已被弃用,因此最好使用 AppCompatActivity。
    • @IntelliJAmiya 的回答太好了
    【解决方案4】:

    这样做

        // Set a Toolbar to replace the ActionBar.
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    
        // Find our drawer view
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        NavigationView nvDrawer = (NavigationView) findViewById(R.id.nvView);
        setupDrawerContent(nvDrawer);
    
        //---- Open Drawer on clic icon BUT CAUSE NULLPOINT EXEPTION--- //
    
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    

    也改变你的布局

    <!-- This LinearLayout represents the contents of the screen  -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <!-- The ActionBar displayed at the top -->
        <include
              layout="@layout/toolbar"
              android:layout_width="match_parent"
              android:layout_height="wrap_content" /> 
    
          <!-- The main content view where fragments are loaded -->
        <FrameLayout
            android:id="@+id/flContent"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>
    
    <!-- The navigation drawer that comes from the left -->
    <!-- Note that `android:layout_gravity` needs to be set to 'start' -->
    <android.support.design.widget.NavigationView
        android:id="@+id/nvView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@android:color/white"
        app:menu="@menu/drawer_view"
        app:headerLayout="@layout/nav_header"
        />
    

    【讨论】:

    • 我刚刚尝试过,但还是一样的 pb FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.erik.test2/com.example.erik.test2.MainActivity}: java.lang.NullPointerException ...... Caused by: java.lang.NullPointerException at android.support.v7.widget.ToolbarWidgetWrapper.&lt;init&gt;(ToolbarWidgetWrapper.java:98) at ....
    【解决方案5】:

    您没有获得操作栏,请从您的 xml 中取消注释以下代码。

       <!--  <include
                  layout="@layout/toolbar"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content" /> -->
    

    也使用当前您正在使用 NoActionBar 的默认主题

    【讨论】:

      【解决方案6】:

      你正在使用AppCompat。所以,使用这个:

      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
      

      【讨论】:

        【解决方案7】:

        当您使用支持库中的AppCompactActivity 时。所以你需要使用getSupportActionBar()获取 ActionBar 实例

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
         getSupportActionBar().setHomeButtonEnabled(true);
        

        既然你已经给出了 NoActionBar 主题。取消注释工具栏包括您需要添加工具栏的相关内容。要么给 Theme with ActionBar 而不是 NoActionBar。或在布局中提供工具栏并添加它。

        <android.support.v4.widget.DrawerLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/drawer_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        
            <!-- This LinearLayout represents the contents of the screen  -->
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">
        
                <!-- The ActionBar displayed at the top -->
                   <include
                      layout="@layout/toolbar"
                      android:layout_width="match_parent"
                      android:layout_height="wrap_content" />  
        
                  <!-- The main content view where fragments are loaded -->
                <FrameLayout
                    android:id="@+id/flContent"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />
            </LinearLayout>
        
            <!-- The navigation drawer that comes from the left -->
            <!-- Note that `android:layout_gravity` needs to be set to 'start' -->
            <android.support.design.widget.NavigationView
                android:id="@+id/nvView"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_gravity="start"
                android:background="@android:color/white"
                app:menu="@menu/drawer_view"
                app:headerLayout="@layout/nav_header"
                />
        </android.support.v4.widget.DrawerLayout>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多