添加侦听器以切换操作栏

时间:2014-01-28 06:30:41

标签: android

我已添加切换到此活动的操作栏

switch layout.xml是

 <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是

<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。 如何在菜单中添加监听器?

1 个答案:

答案 0 :(得分:9)

错误:

因为您在项目中采用了动作布局,所以无法直接找到。

switch1 = (Switch) findViewById(R.id.switch1);

正确:

Switch switch1= (Switch)menu.findItem(R.id.myswitch).getActionView().findViewById(R.id.switch1);