2016-03-02 24 views
3

我在我的應用程序中使用了導航視圖。在導航視圖中的標題重複了兩次,但我實際上刪除了它(app:headerLayout =「@ layout/header」)在xml中。我想從導航視圖的標題中實施操作(如按鈕)。導航視圖中的標題重複android

在代碼我已經這樣寫

mNavigationView = (NavigationView) findViewById(R.id.navigation_view); 
    headerView = mNavigationView.inflateHeaderView(R.layout.bp_header); 
    googele_plus = (ImageButton) headerView.findViewById(R.id.google_p); 
    facebook = (ImageButton) headerViewfindViewById(R.id.fb); 

頭下面

Header repetition

我得到的NullPointerException錯誤喜歡如果headerView從圖像按鈕 除去任何建議或溶液將不勝感激

回答

2

將您的支持庫更新至23.1.1或更高版本。

在這之後,你可以做到這一點 -

添加headerview在應用程序:headerLayout = 「@佈局/頭」 裏面NavigationView。

然後,您可以通過訪問它,

mNavigationView = (NavigationView) findViewById(R.id.navigation_view); 
    View headerView = mNavigationView.getHeaderView(0) 

    googele_plus = (ImageButton) headerView.findViewById(R.id.google_p); 
    facebook = (ImageButton) headerView.findViewById(R.id.fb); 

編號:https://code.google.com/p/android/issues/detail?id=190226#c31

1

嗯,我也得到了NPE與NavigationView頭,我在佈局app:headerLayout="@layout/header"添加頁眉

爲了擺脫工作時這個NPE我開始像以下一樣以編程方式添加頭部

View header = LayoutInflater.from(this).inflate(R.layout.bp_header, null); 
mNavigationView.addHeaderView(header); 
googele_plus = (ImageButton) header.findViewById(R.id.google_p); 

Happy_Coding;

1
You may have header layout in xml and also you are adding header from java like 

    headerView = mNavigationView.inflateHeaderView(R.layout.bp_header); 

    So just remove above line from java and add it through the xml 
    You can add following in your xml  

<include 
android:id="@+id/header" 
layout="@layout/navigation_header" /> 

    and then in java create ref like below   



     googele_plus = (ImageButton) findViewById(R.id.google_p); 
     facebook = (ImageButton) findViewById(R.id.fb); 

    Clean and Build the project and then run 
1

看起來像你創建標題2次。我遇到過同樣的問題。

headerView = mNavigationView.inflateHeaderView(R.layout.bp_header); 

此行^實際上在運行時創建新的View。我相信你在XML中創建了相同的頭文件。嘗試從XML中刪除headerView。這將解決你的問題。

0

您可能會被稱爲導航視圖標題設置功能兩次。所以它創造了兩次。

如果你在onStart()方法中寫入設置導航標題視圖,請在onCreate()方法中刪除並寫入。

如果您去其他活動並返回,onStart會多次撥打電話。 所以它會多次創建標題。 或者檢查您的代碼是否多次調用該代碼。