【发布时间】:2017-09-10 09:33:32
【问题描述】:
我在操作栏中有开关,它工作正常,但我想通过在 XML android:checked="true" 和代码中设置来默认检查
Switch switchButton=new Switch(getActivity());
switchButton.setEnabled(true);
当应用程序启动时,默认情况下始终未选中。这是我的开关代码
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.switch_menu,menu);
MenuItem switchItem=menu.findItem(R.id.toggle_loc);
Switch switchButton=new Switch(getActivity());
switchButton.setEnabled(true);
MenuItemCompat.setActionView(switchItem,switchButton);
switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
Log.d(TAG,"Switch Button Is Checked");
}
else {
Log.d(TAG,"Switch Button Is UnChecked");
}
}
});
R.menu.switch_menu
<?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/toggle_loc"
android:title=""
android:visible="true"
app:actionLayout="@layout/switch_button"
app:showAsAction="ifRoom">
</item>
</menu>
布局/switch_button"
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content">
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/Switch_Location"
android:enabled="true"
android:checked="true"
/>
</RelativeLayout>
请帮我把这个开关设为默认选中。
【问题讨论】:
-
你的
theme里面有什么? -
@Yupi 抱歉,我删除了该行,因为主题是空白的,所以没有效果
-
下面的答案没有解决您的问题?
标签: android android-layout button menu android-actionbar