0
我试图在Android应用程序的工具栏中向开关添加“OnCheckedChangeListener”。但是,如果我点击交换机没有得到Android监视器(logcat)中的日志输出。日志中也没有例外。 在MainActivity:OnCheckedChangeListener不能与工具栏中的开关一起使用
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>
谢谢您的帮助!
你在哪里初始化工具栏? –
你的意思是? '@Override public boolean onCreateOptionsMenu(菜单菜单){ //充气菜单;这会将项目添加到操作栏(如果存在)。 getMenuInflater()。inflate(R.menu.main,menu); 返回true;}' – Mika119
没有你工具栏= findViewById(R.id.toolbar);'和'setSupportActionBar(工具栏);' –