导航抽屉出错

时间:2016-02-11 14:29:30

标签: android

您好我是一名年轻的比利时开发人员,并且目前正在关注YouTube上的教程来创建抽屉导航,但在启动模拟器时我会遇到错误。 This是教程。

以下是错误:

02-10 11:31:12.432 2297-2297/com.example.flori.mylordring E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.flori.mylordring, PID: 2297
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.flori.mylordring/com.example.flori.mylordring.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayShowHomeEnabled(boolean)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayShowHomeEnabled(boolean)' on a null object reference
    at com.example.flori.mylordring.MainActivity.onCreate(MainActivity.java:31)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

主要代码:

package com.example.flori.mylordring;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


private static ImageButton imgView;
private int test;
int [] images = {R.drawable.im1,R.drawable.im2,R.drawable.im3,R.drawable.im4,R.drawable.im5,R.drawable.im6,R.drawable.im7};


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DrawerLayout drawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
                Snackbar.make(view, "Rolololo", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }



public void image(View view){
imgView=(ImageButton)findViewById(R.id.imageButton);
imgView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
test++;
test = test % images.length;
imgView.setImageResource(images[test]);
            }
        }
        );
    }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
    }

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
 // automatically handle clicks on the Home/Up button, so long
 // as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
        }

return super.onOptionsItemSelected(item);
    }
}

活动代码(我有2个不同的活动,这是content_main,我也有activity_main):

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawerLayout"
android:background="#e2656262"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.flori.mylordring.MainActivity"
tools:showIn="@layout/activity_main">

    <FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragmentholder">
    </FrameLayout>

    <ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/navlist"
android:background="#dedede"
android:layout_gravity="start"
/>

    <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />

    <ImageButton
android:onClick="image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/im1"
android:background="@android:color/transparent"
android:layout_above="@+id/textView"
android:layout_centerHorizontal="true" />

</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.flori.mylordring">

    <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"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

**</manifest>

和my2 styles.xml: 这是我的style.xml:**

<resources>

    <!-- Base application theme. -->
    <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>
    </style>

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

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

</resources>

Style.xml(V21):

<resources>>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>

</resources>

2 个答案:

答案 0 :(得分:3)

在这部分代码中:

ActionBar actionBar = getSupportActionBar(); //will return null
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);//why set it after you call getSupportActionBar?

如上所示,在将工具栏设置为操作栏之前,您将获得操作栏,该操作栏将返回null。

您需要切换它们,以便从工具栏中获取参考。

答案 1 :(得分:0)

或者换句话说,您可以使用getSupportActionBar()

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // First initialize the Toolbar
setSupportActionBar(toolbar); // Set as SupportActionBar

getSupportActionBar().setDisplayShowHomeEnabled(true); // do your stuffs
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

第二个问题是:

app:layout_behavior="@string/appbar_scrolling_view_behavior"

您为Drawer设置了它并且它不应该在那里,请查看此链接:

https://github.com/codepath/android_guides/wiki/Handling-Scrolls-with-CoordinatorLayout#expanding-and-collapsing-toolbars

  

app:layout_behavior添加到RecyclerView或任何其他支持的视图   嵌套滚动的内容,例如NestedScrollView。支持库   包含特殊的字符串资源   映射到的@string/appbar_scrolling_view_behavior   AppBarLayout.ScrollingViewBehavior,用于通知   在此特定视图上发生滚动事件时的AppBarLayout