如何在动作栏android中添加开关监听器?

时间:2017-06-11 19:18:22

标签: android android-switch

我正在尝试在操作栏中为我的开关添加一个监听器,因为我已经在StackOverflow上阅读了很多关于它的答案但是我的应用程序在下面点崩溃了。

我的主菜单xml

background:
linear-gradient(-45deg, white,white 25%, red 25%, red), 
linear-gradient( 45deg, white,white 25%, red 25%, red);

我的开关布局

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<item
    android:id="@+id/myswitch"
    android:title=""
    app:showAsAction="always"
    app:actionLayout="@layout/switch_layout"/>
</menu>

我的创建选项菜单是

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<android.support.v7.widget.SwitchCompat
    android:id="@+id/switchForActionBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="" />
</RelativeLayout>

经常调试我发现切换mainSwitchOnOffSw =(Switch)view.findViewById(R.id.switchForActionBar); 这一行会导致应用程序崩溃。我希望我的问题现在很明确。我想将一个监听器附加到我的操作栏开关,但我无法获得该开关对象的实例。以上是StackOverflow上大多数答案的指导方式。任何有关这方面的帮助将受到高度赞赏。

谢谢

1 个答案:

答案 0 :(得分:2)

Switch mainSwitchOnOffSw = (Switch) view.findViewById(R.id.switchForActionBar);

应该是

SwitchCompat mainSwitchOnOffSw = (SwitchCompat) view.findViewById(R.id.switchForActionBar);

在布局中使用SwitchCompat。