您好我在我的应用程序中创建导航抽屉.现在我有问题如何以编程方式更改MenuItem导航抽屉的每个图标?如果在Xml中菜单如下:
和这样的活动:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setIc navigationView.setNavigationItemSelectedListener(this); setFragmentArtikel(); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_input_berita) { } else if (id == R.id.nav_logout) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
所以如何编程.改变图标android:icon="@drawable/ic_nav_input_berita"
和android:icon="@drawable/ic_nav_input_logout"
?对不起我的英语不好
这样做:
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); Menu menu = navigationView.getMenu(); MenuItem nav_input_beritaItem = menu.findItem(R.id.nav_input_berita); nav_input_beritaItem .setIcon(R.drawable.ic_nav_input_berita); MenuItem nav_logoutItem = menu.findItem(R.id.nav_input_logout); nav_logoutItem .setIcon(R.drawable.ic_nav_input_logout);
就这样