因此,我試圖在菜單中添加一個開關,並且我希望(至少在此時)在開關打開或關閉時做一個Toast。目前沒有發生,我不太清楚爲什麼。菜單中的開關按鈕,如何至少在真或假時烤麪包
我添加了我的菜單項和開關佈局的代碼。
請指教,謝謝!
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.switch, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.myswitch:
Switch simpleSwitch = (Switch) findViewById(R.id.menuSwitch);
simpleSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
Toast.makeText(ModularActivity.this, "This is on", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ModularActivity.this, "This is off", Toast.LENGTH_SHORT).show();
}
}
});
return true;
case android.R.id.home:
// Navigate back to parent activity (CatalogActivity)
NavUtils.navigateUpFromSameTask(this);
return true;
}
return true;
}
這是菜單項:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/myswitch"
android:title=""
app:showAsAction="always"
app:actionLayout="@layout/activity_switch_layout"
/>
這裏是activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="2dp"
android:textStyle="bold"
android:textColor="@android:color/white"
android:text="WHITE"/>
<Switch
android:id="@+id/menuSwitch"
android:checked="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:text="GREEN"
android:layout_marginRight="5dp"
android:textStyle="bold"
android:textColor="@color/green"/>
</LinearLayout>