Java 如何访问NavigationView中的子按钮
如何访问NavigationView中RelativeLayout视图的子级按钮?但是,我可以通过以下方式访问标题视图中的文本视图:Java 如何访问NavigationView中的子按钮,java,android,xml,Java,Android,Xml,如何访问NavigationView中RelativeLayout视图的子级按钮?但是,我可以通过以下方式访问标题视图中的文本视图: NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); View header=navigationView.getHeaderView(0); TextView tvUserName = (TextView)header.findViewById(R.id.dra
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View header=navigationView.getHeaderView(0);
TextView tvUserName = (TextView)header.findViewById(R.id.drawer_user_name);
是否也有相同的方法访问按钮?
这是我的布局->
下面是布局的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>
是的,你可以打电话
Button btn1 = (Button)navigationView.findViewById(R.id.btn1);
或者干脆
Button btn1 = (Button)findViewById(R.id.btn1);
抱歉,此错误来自NavigationView NavigationView=(NavigationView)findViewById(R.id.nav_视图);视图标题=navigationView.getHeaderView(0);TextView tvUserName=(TextView)header.findViewById(R.id.drawer\u user\u name);我仍然得到它:java.lang.RuntimeException:无法启动activity ComponentInfo{in.mbedded.mynav/in.mbedded.mynav.MainActivity}:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'android.view.view android.view.view.findViewById(int)'。我不确定我理解你说的是什么意思,很抱歉您不必使用视图的直接父级来查找视图。要获取用户名textview,只需调用textview tvUserName=(textview)findViewById(R.id.drawer\u user\u name);谢谢,没有像你说的那样直接向直系父母求助。