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>
很抱歉,這錯誤來自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。查看空對象引用上的android.view.View.findViewById(int)' –
我不確定我是否理解你的意思,對不起! 您不必擁有視圖的直接父級即可查找視圖。 要獲取用戶名textview,您可以簡單地調用 TextView tvUserName =(TextView)findViewById(R.id.drawer_user_name); –
感謝它的工作,沒有提到直接的父母,因爲你告訴。 –