我在我的Android应用中使用SwitchPreference时发现了一个奇怪的问题。偏好设置中有多个SwitchPreference。
当我使用PreferenceActivity的默认布局时,一切都运行得很好。但是在我将自定义布局设置为偏好设置活动后,这些开关开始同时改变,无论你点击哪个。我正在一台基于ARM的平板电脑上测试它。同时我也在我的Android手机上测试过,结果也一样。
这是怎么回事!
以下是我偏好设置的自定义布局(`setting.xml`):
在代码中,我只是设置了自定义布局。
这是偏好设置的截图,无论点击哪个开关,这两个开关总是同时改变。
当我使用PreferenceActivity的默认布局时,一切都运行得很好。但是在我将自定义布局设置为偏好设置活动后,这些开关开始同时改变,无论你点击哪个。我正在一台基于ARM的平板电脑上测试它。同时我也在我的Android手机上测试过,结果也一样。
这是怎么回事!
以下是我偏好设置的自定义布局(`setting.xml`):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/button1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button" />
<Button
android:id="@+id/button2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button" />
</LinearLayout>
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
以及PreferenceScreen
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<SwitchPreference
android:key="switch1"
android:summary="This is switch 1"
android:title="Switch 1" />
<SwitchPreference
android:key="switch2"
android:summary="This is switch 2"
android:title="Switch 2" />
</PreferenceScreen>
在代码中,我只是设置了自定义布局。
public class SettingsActivity extends PreferenceActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setting);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setupSimplePreferencesScreen();
}
private void setupSimplePreferencesScreen() {
addPreferencesFromResource(R.xml.pref_general);
}
}
这是偏好设置的截图,无论点击哪个开关,这两个开关总是同时改变。
![偏好设置截图](https://istack.dev59.com/v2Igs.webp)