簡體   English   中英

嘗試添加導航抽屜時出現NullPointerException(Android)

[英]NullPointerException when trying to add a Navigation Drawer (Android)

我有點卡住了。 我一直在遵循一些教程,並最終制作了一個DrawerLayout如下所示:

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

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

</FrameLayout>

<ListView
    android:id="@+id/list"
    android:entries="@array/menuitems"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="left">
</ListView>
</android.support.v4.DrawerLayout>

我希望每當按下工具欄上的漢堡包圖標時都可以滑動該菜單,因此我在Activity中設置了onClickListener:

    hamburgerIcon = (ImageView) findViewById(R.id.hamburger);
    hamburgerIcon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                 String[] osArray = { "Bla", "Bla", "alB", "alB", "BLA" };
                 mAdapter = new ArrayAdapter<>(this,  android.R.layout.simple_list_item_1, osArray);
                 mDrawerList = (ListView) findViewById(R.id.list);
                 mDrawerList.setAdapter(mAdapter);
        }
    };

當我嘗試初始化ListView (mDrawerList)時得到NullPointer-我確定這是因為我正在使用的Activity使用與Navigation_drawer.xml不同的布局,因此無法在xml中找到ListView 。 我的問題是,如何使用主(不同)布局使用導航抽屜布局?

歡迎任何提示,謝謝。

編輯:我使用此標記在主布局中包括DrawerLayout

    <include layout="@layout/navigation_drawer"
        android:id="@+id/navdraw"/>

但是,現在打開主布局時出現“ RuntimeException”,原因是“ android.view.InflateException:二進制XML文件第2行:膨脹類android.support.v4.DrawerLayout時出錯”-然后它抱怨setContentView( ..)行中的主要活動。

我嘗試在gradle腳本中添加依賴項

compile 'com.android.support:support-v4:20.0.0'

但是用紅色下划線標明,“支持庫不應使用比targetSdkVersion(22)低的版本(20)”。

有任何想法嗎?

 hamburgerIcon = (ImageView) findViewById(R.id.hamburger);
  mDrawerList = (ListView) findViewById(R.id.list);
    hamburgerIcon.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
             String[] osArray = { "Bla", "Bla", "alB", "alB", "BLA" };
                 mAdapter = new ArrayAdapter<>(this,  android.R.layout.simple_list_item_1, osArray);
                           mDrawerList.setAdapter(mAdapter);
        }
    };

再試一次

看起來不是navigation_drawer.xml的主要布局? 您可以使用include標記並設置id 然后嘗試findViewById(include_id).findViewById(R.id.list)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM