簡體   English   中英

OnCheckedChangeListener不適用於工具欄中的開關

[英]OnCheckedChangeListener don't work with a Switch in the Toolbar

我試圖將“ OnCheckedChangeListener”添加到Android應用程序工具欄中的開關。 但是,如果我單擊“開關”,則不會在Android Monitor(logcat)中獲得日志輸出。 日志中也沒有例外。 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>

謝謝您的幫助!

我必須在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);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM