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); –
感谢它的工作,没有提到直接的父母,因为你告诉。 –