Android- 将导航抽屉添加到自定义工具栏时应用崩溃

Android- app crashes while adding a navigation drawer to a custom toolbar

我制作了一个自定义工具栏和它的从右到左。它看起来像这样:

我希望在单击右侧图标时出现导航抽屉。但是当我将导航抽屉添加到应用程序时,它崩溃了。我尝试了很多东西,也搜索了很多,但没有用。 如果有人能帮助我就好了。

这是我的代码:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.playpersia.mycustomizedtoolbar.MainActivity"
  >

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


  <android.support.v4.widget.DrawerLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:openDrawer="end"
    android:fitsSystemWindows="true"
    android:id="@+id/right_drawer">

   <!-- Main layout -->
   <FrameLayout
    android:id="@+id/main_fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

 <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/toolbar"
android:text="Hello"/>

  </FrameLayout>


    <!-- Nav drawer -->
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="right|end" >

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/header_drawer"
            android:src="@drawable/my_image" />

        <ListView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="end"
            android:id="@+id/list_view"
            android:entries="@array/pages" />
    </LinearLayout>

   </android.support.v4.widget.DrawerLayout>

 </LinearLayout>

right_drawer.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:openDrawer="end"
android:fitsSystemWindows="true"
android:id="@+id/right_drawer"
>
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/header_drawer"
        android:src="@drawable/my_image" />
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="end"
        android:id="@+id/list_view"
        android:entries="@array/pages" />

  </android.support.v4.widget.DrawerLayout>

MainActivity.java

 package com.playpersia.mycustomizedtoolbar;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.zip.Inflater;

public class MainActivity extends AppCompatActivity implements  NavigationView.OnNavigationItemSelectedListener {
    private Toolbar toolbar;
    public ListView listView;
    public String[] pages;
    ArrayAdapter<String> arrayAdapter;
    public ImageView menu_icon;
    public ImageView  back_arrow;
    public boolean mSlideState;
    private DrawerLayout drawerLayout;
    public ActionBarDrawerToggle _mDrawerTg;
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        menu_icon = (ImageView) findViewById(R.id.menu_icon);
        back_arrow = (ImageView) findViewById(R.id.back_button);
        drawerLayout =(DrawerLayout) findViewById(R.id.right_drawer);
        pages =getResources().getStringArray(R.array.pages);
        _mDrawerTg =new ActionBarDrawerToggle(this, drawerLayout,
                null, R.string.drawer_open, R.string.drawer_close){
            public void onDrawerClosed(View view){
                mSlideState=false;
            }
            public void onDrawerOpened (View drawerView){
                super.onDrawerOpened(drawerView);
                mSlideState=true;
            }        };

       listView = (ListView) findViewById(R.id.list_view);

        listView.setAdapter(new ArrayAdapter<String>(this,R.layout.drawer_list_item,pages));

        drawerLayout.setDrawerListener(_mDrawerTg);
        _mDrawerTg.syncState();
        menu_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mSlideState){
                    drawerLayout.closeDrawer(GravityCompat.END);
                }else{
                    drawerLayout.openDrawer(GravityCompat.END);                }            }        });    }


    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        _mDrawerTg.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        _mDrawerTg.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Pass the event to ActionBarDrawerToggle, if it returns
        // true, then it has handled the app icon touch event
        if (_mDrawerTg.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle your other action bar items...

        return super.onOptionsItemSelected(item);
    }
}

更新 logcat:

01-18 12:34:25.386 29949-29949/com.playpersia.mycustomizedtoolbar  
E/AndroidRuntime: FATAL EXCEPTION: main Process:
com.playpersia.mycustomizedtoolbar, PID: 29949 java.lang.RuntimeException: 
Unable to start activityComponentInfo{com.playpersia.mycustomizedtoolbar/com.playpersia.mycustomizedtool   
 bar.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual
 method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on    a null object reference at 
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)at
 android.app.ActivityThread.access0(ActivityThread.java:156)at    android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)at
android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5373)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)at   com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method   'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null   object reference at com.playpersia.mycustomizedtoolbar.MainActivity.onCreate(MainActivity.java:53)
at android.app.Activity.performCreate(Activity.java:5990)
at    android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2332)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442) 
at android.app.ActivityThread.access0(ActivityThread.java:156) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:211) 
at android.app.ActivityThread.main(ActivityThread.java:5373) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372)at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815) 

更新 2

现在我有了这个工具栏,当我点击抽屉打开和关闭的右侧图标时, right side drawer

这应该是你的 MainLayout 因为你正在使用 DrawerLayout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/right_drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <!-- Your contents, for example, CoordinatorLayout with material design -->

    <!-- And after main Contents, here you can use NavigationDrawer also -->

</android.support.v4.widget.DrawerLayout>

使用您的内容代替注释代码。

你做错了,看看:

http://developer.android.com/training/implementing-navigation/nav-drawer.html#DrawerLayout

To add a navigation drawer, declare your user interface with a DrawerLayout object as the root view of your layout. Inside the DrawerLayout, add one view that contains the main content for the screen (your primary layout when the drawer is hidden) and another view that contains the contents of the navigation drawer.

For example, the following layout uses a DrawerLayout with two child views: a FrameLayout to contain the main content (populated by a Fragment at runtime), and a ListView for the navigation drawer.

示例:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <!-- The navigation drawer -->
    <ListView android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#111"/>
</android.support.v4.widget.DrawerLayout>

当然,您可能需要查看此实现的 Material 设计指南

https://www.google.com/design/spec/patterns/navigation-drawer.html

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference at com.playpersia.mycustomizedtoolbar.MainActivity.onCreate(MainActivity.java:53)

onCreate 方法中,您的 listView 对象为空。

您需要添加

listView = (ListView) findViewById(R.id.list_view);

之前

listView.setAdapter(new ArrayAdapter<String (this,R.layout.drawer_list_item,pages));

更新:

将您的 activity_main.xml 更改为:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

    <android.support.v4.widget.DrawerLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:openDrawer="end"
        android:fitsSystemWindows="true"
        android:id="@+id/right_drawer">

        <!-- Main layout -->
        <FrameLayout
            android:id="@+id/main_fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/toolbar"
                android:text="Hello"/>

        </FrameLayout>

        <!-- Nav drawer -->
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="left|start" >

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/header_drawer"
                android:src="@drawable/my_image" />

            <ListView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="end"
                android:id="@+id/list_view"
                android:entries="@array/pages" />
        </LinearLayout>

    </android.support.v4.widget.DrawerLayout>

</LinearLayout>