OnCheckedChangeListener不能与工具栏中的Switch一起使用

时间:2016-08-02 15:11:48

标签: java android android-layout onclicklistener

我尝试将“OnCheckedChangeListener”添加到Android应用工具栏的Switch中。但是如果我点击Switch,就不要在Android Monitor(logcat)中获取Log输出。日志中也没有例外。 MainActivity:

LayoutInflater factory = getLayoutInflater();
View textEntryView = factory.inflate(R.layout.toolbar_switch, null);

toolbarSwitch = (Switch) textEntryView.findViewById(R.id.switch_toolbar);
toolbarSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        Log.d("SMSAT", "Test");
    }
});

这是交换机的布局:

 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="1">
    <Switch
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/switch_toolbar"
        android:text=""
        android:layout_weight="0.16"
        android:checked="true" />

    </LinearLayout>

菜单:

<?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">

<item
    android:id="@+id/menu_switch_toolbar"
    android:title="@string/menu_switch"
    app:showAsAction="always"
    app:actionLayout="@layout/toolbar_switch"></item>

</menu>

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我必须在onCreateOptionsMenu方法中移动我的代码。

以下是代码:

 @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.

    MenuInflater inflater = getMenuInflater();
   inflater.inflate(R.menu.main, menu);

    View textEntryView = menu.findItem(R.id.menu_switch_toolbar).getActionView();

    toolbarSwitch = (Switch) textEntryView.findViewById(R.id.switch_toolbar);
    toolbarSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            Log.d("SMSAT", "Test");
        }
    });

    return super.onCreateOptionsMenu(menu);

}