无法访问nav_header_main.xml

时间:2017-08-22 09:35:01

标签: android

任何人都可以帮我解决问题,我在我的代码中做了一切来访问它们

public class MainActivity extends BaseActivity
implements NavigationView.OnNavigationItemSelectedListener {

private ImageView mDisplayImageView;
private TextView mNameTextView;
private TextView mEmailTextView;

NavigationView navigationView = (NavigationView) 
findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
 View navHeaderView = navigationView.getHeaderView(0);
 initNavHeader(navHeaderView);
}
private void initNavHeader(View view) {
mDisplayImageView = (ImageView) 
view.findViewById(R.id.imageView_display);
mNameTextView = (TextView) view.findViewById(R.id.textview_name);
mEmailTextView = (TextView) view.findViewById(R.id.textView_email);
}

2 个答案:

答案 0 :(得分:3)

你可以像这样使用onnavigationitem选择的方法...... firast of all在create method中定义导航视图..

 NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        navigationView.setCheckedItem(R.id.nav_frag1);

然后创建方法......

public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        logo=(ImageView)findViewById(R.id.logo);
        logo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getBaseContext(),"Unable to get Permission",Toast.LENGTH_LONG).show();
            }
        });
        int id = item.getItemId();
        fragment = null;

        if (id == R.id.nav_frag1) {
            fragment = new HomeFragment();
        }
        /*else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }*/

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

答案 1 :(得分:1)

试试这个,您可以像这样访问 nav_header_main.xml的图片和文字视图

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);       

mNameTextView = (TextView) navigationView.getHeaderView(0).findViewById(R.id.textview_name);
mEmailTextView = (TextView) navigationView.getHeaderView(0).findViewById(R.id.textView_email);
mDisplayImageView = (ImageView)navigationView.getHeaderView(0).findViewById(R.id.imageView_display);