2017-02-09 4 views
0

NavigationView内のRelativeLayoutビューの子ボタンにはどうすればアクセスできますか?しかし、私は使用してヘッダービュー内TextViewsにアクセスすることができる午前:NavigationView内の子であるボタンにアクセスする方法

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); 
View header=navigationView.getHeaderView(0); 
TextView tvUserName = (TextView)header.findViewById(R.id.drawer_user_name); 

もボタンにアクセスするための任意のと同じ方法はありますか? は、ここに私のレイアウトである - >Image of the layout from which i want to access buttons

、ここでレイアウトのxmlです:

<android.support.design.widget.NavigationView 
    android:id="@+id/nav_view" 
    android:layout_width="300dp" 
    android:layout_height="match_parent" 
    android:layout_gravity="start" 
    android:fitsSystemWindows="true"> 

    <RelativeLayout 
     android:id="@+id/rl" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical"> 
     <include layout="@layout/nav_header_main" 
      android:id="@+id/header"/> 

     <Button 
      android:id="@+id/btn1" 
      android:layout_below="@id/header" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:text="Button1" 
      /> 
     <Button 
      android:id="@+id/btn2" 
      android:layout_below="@id/btn1" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:text="Button2"/> 
     <Button 
      android:id="@+id/btn3" 
      android:layout_below="@id/btn2" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:text="Button3"/> 
     <Button 
      android:id="@+id/btn4" 
      android:layout_below="@id/btn3" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:text="Button4"/> 
     <Button 
      android:id="@+id/btn5" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_alignParentBottom="true" 
      android:text="Button5"/> 
    </RelativeLayout> 

</android.support.design.widget.NavigationView> 

答えて

-1

うん、あなただけの

Button btn1 = (Button)navigationView.findViewById(R.id.btn1); 

または単に

Button btn1 = (Button)findViewById(R.id.btn1); 
+0

申し訳ありませんが、これを呼び出すことができますNavigationViewからエラーが発生しました。navigationView =(NavigationView)findViewById(R.id.nav_view); ビューのヘッダ= navigationView.getHeaderView(0); TextView tvUserName =(TextView)header.findViewById(R.id.drawer_user_name);私はまだそれを取得しています:java.lang.RuntimeException:アクティビティを開始することができませんComponentInfo {in.mbedded.mynav/in.mbedded.mynav.MainActivity}:java.lang.NullPointerException: 'android.view'という仮想メソッドを呼び出そうとしています。 View android.view.findViewById(int) 'nullのオブジェクト参照 –

+0

私はあなたがそのコメントの意味を理解していません、ごめんなさい! ビューを見つけるためにビューの直接の親を持つ必要はありません。 ユーザ名textviewを取得するには、単に と呼ぶことができます。 TextView tvUserName =(TextView)findViewById(R.id.drawer_user_name); –

+0

あなたが言ったように、それは直接の親を参照せずに働いてくれてありがとう。 –

関連する問題