[英]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.