我已经将开关添加到活动的操作栏中,如下所示:
开关布局文件如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<Switch
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</RelativeLayout>
Menu.xml is
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
<item
android:id="@+id/myswitch"
android:title=""
android:showAsAction="always"
android:actionLayout="@layout/switch_layout"
/>
</menu>
在Java文件中,我有以下代码:
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.Menu, menu);
switch1 = (Switch) findViewById(R.id.switch1);
if(switch1 == null){
Toast.makeText(this, "Null", Toast.LENGTH_SHORT).show();
}
// switch1.setOnCheckedChangeListener(this);
return true;
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(this, "Monitored switch is " + (isChecked ? "on" : "off"),
Toast.LENGTH_SHORT).show();
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.switch1:
Toast.makeText(this, "here", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
弹出框中显示 null。 如何在菜单中添加监听器?