在操作栏中添加开关监听器

4

我已经将开关添加到活动的操作栏中,如下所示:

开关布局文件如下:

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


请发布您的Activity的“implements”部分。 - Paresh Mayani
公共类TemperatureActivity扩展自Activity并实现OnCheckedChangeListener接口 - Nalini Wanjale
1个回答

9

错误:

由于您在项目中使用了Action布局,因此无法直接找到View。

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

Correct:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接