NavigationView get/find header layout

前端 未结 7 986
感情败类
感情败类 2020-11-22 02:57

In my NavigationView I have a header layout with id \'viewId\' with active buttons. To setup those buttons, I do the following in activity\'s onPostCreate:

相关标签:
7条回答
  • 2020-11-22 03:13

    Kotlin version.

    val navView: NavigationView = findViewById(R.id.nav_view)       
    // set User Name
    val headerView: View = navView.getHeaderView(0)
    headerView.txtUserName.text = "User Name Goes here"
    
    0 讨论(0)
  • 2020-11-22 03:15

    Now with the 23.1.1 release of the design support library, you can use

    NavigationView navigationView = (NavigationView) findViewById(R.id.your_nav_view_id);
    View header = navigationView.getHeaderView(0)
    TextView text = (TextView) header.findViewById(R.id.textView);
    
    0 讨论(0)
  • 2020-11-22 03:19

    This is how I did it using ButterKnife and it works for me.

    protected static class HeaderViewHolder {
    
        @BindView(R.id.button)
        Button button;
    
        HeaderViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
    

    and then use this view holder like this :

    View header = navigationView.getHeaderView(0);
    headerViewHolder = new HeaderViewHolder(header);
    
    0 讨论(0)
  • 2020-11-22 03:21
    NavigationView navigationView = findViewById(R.id.your_nav_view);
    View header = navigationView.getHeaderView(0);
    TextView textUsername = header.findViewById(R.id.textView);
    textUsername.setText("you text here ");
    
    0 讨论(0)
  • 2020-11-22 03:32

    For me that was the same situation with 23.1.0, after of update the null pointer exception become. In this case the NavigatorView look like:

    <android.support.design.widget.NavigationView
      android:id="@+id/navigation_view"
      android:layout_height="match_parent"
      android:layout_width="wrap_content"
      android:layout_gravity="start"
      android:fitsSystemWindows="true"
      app:headerLayout="@layout/nav_header"
      app:menu="@menu/menu_nav"/>
    

    I tried the solution proposal by ianhanniballake but it does not work. Then I inflated with the sentence:

    LayoutInflater.from(getContext()).inflate(R.layout.nav_header, mNavigationView);
    

    After that, I can find by id all views defined in nav_heardlayout .

    0 讨论(0)
  • 2020-11-22 03:33

    In Kotlin @Francois Dermu code be like

    val navigationView : NavigationView = findViewById(R.id.your_nav_view_id);
    val header = navigationView.getHeaderView(0)
    val textView = header.findViewById<TextView>(R.id.textView)
    
    0 讨论(0)
提交回复
热议问题