スイッチにメニューを追加しようとしています。スイッチがオンまたはオフのときにトーストを(少なくともこの時点で)したいと思っています。現在、何も起こっていないと私はなぜあまり理由がわからない。メニューのスイッチボタン、少なくともトゥルーまたは偽のときのトースト方法
メニュー項目とスイッチのレイアウトのコードを追加しました。
ありがとうございました!ここで
@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>