Android自帶抽屜佈局及NavigationView的使用

在新版本的android sdk中,谷歌爲開發者們帶來了不少好用的東西,好比原生抽屜佈局,下拉刷新等等,對很不樂意去網上找各類各樣亂七八糟的第三方控件的某人真是挺不錯的-。-2333html

圖片描述

使用起來樣子大概是這樣的android

使用方式也很是簡單,若是想省事的話直接利用add Navigation Drawer Activity就好了。
建立活動後,咱們可能會對其中的控件動態更新,可是接下來問題就來了。app

獲取NavigationView的中的控件出現空指針異常

咱們在Navigation Drawer Activity中獲取控件,第一反應就是直接在onCreateView裏調用findViewById,例如我想獲取上圖中的TextView,假如id爲tv_user佈局

TextView tv = (TextView)findViewById(R.id.tv_user);

而後給tv改下字spa

tv.setText("Hello world");

這時候就會報錯說tv爲空指針。問題引發其實很是簡單,是由於在activity剛建立的時候,Dawer實際上是沒有打開的,因此佈局沒有初始化,天然也不能找到其中的空間。通常這種狀況咱們爲了獲取這類未初始佈局裏的空間會使用inflate方法,這裏其實處理是相似的,後面會提到。指針

咱們首先了解一下NavigationView的使用,新建一個抽屜活動後,咱們能夠看到主界面的佈局文件是這樣的code

<?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:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">
    
        <include
            layout="@layout/app_bar_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:headerLayout="@layout/nav_header_main"
            app:menu="@menu/activity_main_drawer" />
    
    </android.support.v4.widget.DrawerLayout>

其實這裏的NavigationView就是左邊抽屜拉出來後的佈局了~能夠看到它有兩個屬性app:headerLayout和app:menu
其實這兩個屬性後面就分別是上圖中藍色背景部分的抽屜頭和下面的菜單。要對其編輯也很簡單,進入ID對應的佈局修改便可。xml

操做1:

前面提到的獲取不到控件的方法,能夠在onCreate方法中這樣來獲取htm

View headerLayout = navigationView.inflateHeaderView(R.layout.nav_header_main);
    tv_nav_user = (TextView)headerLayout.findViewById(R.id.tv_nav_username);

經過查看谷歌官方開發文檔咱們還能夠發現幾個方法
http://developer.android.com/reference/android/support/design/widget/NavigationView.html圖片

clipboard.png

這些方法都是對抽屜佈局上的菜單和頭佈局進行操做時可使用的。
同時注意

inflateHeaderView:Inflates a View and add it as a header of the navigation menu.

這也就是說咱們在進行前面的操做1實際上是得到該佈局的同時把其加入到抽屜佈局中去,這樣就會出現下面的狀況:
圖片描述

操做2

解決方法也很簡單,就是在layout文件中去掉

app:headerLayout="@layout/nav_header_main"

而後就能夠獲取到裏面的控件愉快玩耍了~

補充:
其實若是不用上面的方法的話也是能夠直接獲取到header的,能夠調用

View headerView = navigationView.getHeaderView(0);

來得到頭部佈局

相關文章
相關標籤/搜索