[英]Switch in Drawer Navigation bar
但是当我尝试使用此代码访问活动 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();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.