Xamarin Android:无法通过MainActivity的NavigationView设置导航抽屉TextView
解决导航抽屉Header中TextView无法修改内容的问题
我猜你大概率是直接用FindViewById<TextView>(Resource.Id.your_textview_id)来获取控件吧?这就是问题所在——导航头(nav_header)是NavigationView的子视图,不是Activity根视图的直接子元素,直接查找根本找不到控件,自然设置内容不会生效。
下面分两种常见场景给出具体解决步骤:
场景1:导航头通过NavigationView的app:headerLayout静态配置
如果你的main.axml里是这样配置NavigationView的:
<com.google.android.material.navigation.NavigationView android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" app:headerLayout="@layout/nav_header_main" app:menu="@menu/activity_main_drawer" />
那你需要先获取NavigationView的Header视图,再从中查找目标TextView:
// 第一步:获取NavigationView实例 NavigationView navView = FindViewById<NavigationView>(Resource.Id.nav_view); // 第二步:获取导航头的根视图(如果有多个header,用GetHeaderView(index),index从0开始) View headerView = navView.GetHeaderView(0); // 第三步:从headerView中查找目标TextView TextView targetTxt = headerView.FindViewById<TextView>(Resource.Id.nav_header_target_text); // 现在就可以正常设置内容了 targetTxt.Text = "你想要显示的自定义内容";
场景2:动态Inflate并添加导航头
如果是通过代码手动添加导航头,要记得保存Inflate后的视图引用,再从中查找控件:
NavigationView navView = FindViewById<NavigationView>(Resource.Id.nav_view); // Inflate导航头布局 View headerView = LayoutInflater.Inflate(Resource.Layout.nav_header_main, navView, false); // 添加到NavigationView navView.AddHeaderView(headerView); // 从保存的headerView中查找TextView TextView targetTxt = headerView.FindViewById<TextView>(Resource.Id.nav_header_target_text); targetTxt.Text = "动态设置的内容";
额外要排查的细节
- 确认
nav_header.axml里TextView的Id和代码中引用的完全一致,别出现大小写、拼写错误; - 如果是在Fragment中操作,要确保NavigationView已经初始化完成(比如在
OnViewCreated方法中执行,而非OnCreate); - 若使用了DataBinding,要保证绑定变量正确赋值,避免和直接FindViewById的方式冲突。
按照上面的方法调整代码,应该就能解决TextView无法修改的问题了!
内容的提问来源于stack exchange,提问作者Muhammad Yousuf
相关产品推荐
相关产品推荐

