文章轉自http://www.07net01.com/2015/12/1020892.html
在新版本的android sdk中,谷歌爲開發者們帶來了很多好用的東西,比如原生抽屜佈局,下拉刷新等等,對很不樂意去網上找各種各樣亂七八糟的第三方控件的某人真是挺不錯的-。-2333
使用起來樣子大概是這樣的
使用方式也非常簡單,如果想省事的話直接利用add Navigation Drawer Activity就行了。
創建活動後,我們可能會對其中的控件動態更新,但是接下來問題就來了。
獲取NavigationView的中的控件出現空指針異常
我們在Navigation Drawer Activity中獲取控件,第一反應就是直接在onCreateView裏調用findViewById,例如我想獲取上圖中的TextView,假如id爲tv_user
TextView tv = (TextView)findViewById(R.id.tv_user);
然後給tvtv.setText(“Hello world”);就會報錯說tv爲空指針。問題引起其實非常簡單,是因爲在activity剛創建的時候,Dawer其實是沒有打開的,所以佈局沒有初始化,自然也不能找到其中的空間。一般這種情況我們爲了獲取這類未初始佈局裏的空間會使用inflate方法,這裏其實處理是類似的,後面會提到。
我們首先了解一下NavigationView的使用,新建一個抽屜活動後,我們可以看到主界面的佈局文件是這樣的
<?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對應的佈局修改即可。
操作1:
前面提到的獲取不到控件的方法,可以在onCreate方法中這樣來獲取
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
這些方法都是對抽屜佈局上的菜單和頭佈局進行操作時可以使用的。
同時注意
inflateHeaderView:Inflates a View and add it as a header of the navigation menu.
這也就是說我們在進行前面的操作1其實是獲得該佈局的同時把其加入到抽屜佈局中去,這樣就會出現下面的情況:出現的是兩個頭佈局。
操作2
解決方法也很簡單,就是在layout文件中去掉
app:headerLayout=”@layout/nav_header_main”
然後就可以獲取到裏面的控件愉快玩耍了~
View headerLayout = navigationView.inflateHeaderView(R.layout.nav_header_main);
text_xingm = (TextView)headerLayout.findViewById(R.id.text_xingm);
image_touxiang = (ImageView) headerLayout.findViewById(R.id.image_touxiang1);
image_touxiang.setImageResource(R.drawable.ic_test_5);
text_xingm.setText("正常");
出現兩個頭佈局,然後去掉app:headerLayout="@layout/nav_header_main"
解決問題
文章轉自http://www.07net01.com/2015/12/1020892.html