I'm using SwitchPreference in my Android app and found something so weird. There is more than one SwitchPreference in the preference.

When I use the default layout of PreferenceActivity, everything works so well. But after I set custom layout to the preference activity, those Switches begin change together when you click any of them. I'm testing it on a arm-based tablet. Also I test it on my Android phone, It works just so the same.

How does it happens!

Here is my custom layout (setting.xml) for preference:

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical" >

android:layout_width="match_parent"

android:layout_height="wrap_content" >

android:id="@+id/button1"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:text="Button" />

android:id="@+id/button2"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:text="Button" />

android:id="@android:id/list"

android:layout_width="match_parent"

android:layout_height="wrap_content" >

and the PreferenceScreen

android:key="switch1"

android:summary="This is switch 1"

android:title="Switch 1" />

android:key="switch2"

android:summary="This is switch 2"

android:title="Switch 2" />

In the code, I just set the custom layout

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);

}

}

Here is the screenshot of the preference, and the two switch always change at the same time what ever you click each of them.

v2Igs.png

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐