但是当我尝试使用此代码访问活动Oncreate中的Switch时
NavigationView navigationView = findViewById(R.id.nav_view);
try {
((Switch) navigationView.getMenu().findItem(R.id.nav_isactive).getActionView()).setChecked(true);
}
catch (Exception ex)
{
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
}
我有演员表错误:
java.lang.ClassCastException: androidx.appcompat.view.menu.MenuItemImpl cannot be cast to android.widget.Switch
并且在ex.getMessage()上告诉我:无法将linearLayout强制转换为Switch吗?!
NavigationView navigationView = findViewById(R.id.nav_view);
MenuItem menuItem = navigationView.getMenu().findItem(R.id.nav_isactive); // This is the menu item that contains your switch
Switch drawer_switch = (Switch) menuItem.getActionView().findViewById(R.id.m_swisactive);
drawer_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Your logic goes here
Toast.makeText(MainActivity.this, String.valueOf(isChecked), Toast.LENGTH_SHORT).show();
}
});