java - getActionBar().setDisplayHomeAsUpEnabled(true), -> java.lang.NullPointerException 无法解决

标签 java android xml nullpointerexception

我有以下问题:
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>

和 list 代码

<?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>

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

最佳答案

糟糕的方法

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

建议

Since the version 22.1.0, the class ActionBarActivity is deprecated. You should use 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"

Using the Toolbar to replace an ActionBar is pretty straight forward and begins with making sure that the activity extends ActionBarActivity. Also make sure that the theme for this activity is a child of either Theme.AppCompat.NoActionBar or 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

关于java - getActionBar().setDisplayHomeAsUpEnabled(true), -> java.lang.NullPointerException 无法解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34848051/

相关文章:

java - ]]> &lt;![CDATA[ 分散在转换后的 xml 文档上

java - 在 Java 中使用 Aspose 单元动态创建工作表?

java - NetBeans 平台两次捕获一个异常

java - 如何在 Retrofit 2.6 中将列表作为正文发布

php - PHP SimpleXML XPath contains()查找此元素引用的其他元素

javascript - 使用 Google Maps API v3 问题循环标记

java - 检查 SQLite 数据库中是否存在几个值

java - GAE 请求根实体上的 XG 交易

android - 在 Android 中设置动态壁纸时出现奇怪的异常

即使运行其他版本,Android 也总是从 v9 文件夹中获取我的布局