Question

I've run to this strange error:

1 PregerenceFragment in normal activity. In fragment there are two SwitchPreferences. Everything works fine now. But when I override onCreateView method then those switches act as one in meaning of they have always same state - check/uncheck one and another does the same.

Is that know bug or am I doing anything wrong please?

Thanks

preference xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <SwitchPreference
        android:defaultValue="true"
        android:key="@string/key_syncing_wifi"
        android:title="123" />
    <SwitchPreference
        android:defaultValue="false"
        android:key="@string/key_syncing_carrier"
        android:title="234" />

</PreferenceScreen>

fragment layout xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    tools:context=".PreferenceActivity" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:text="123" />

</LinearLayout>

fragment class

public class PreferenceSyncingFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preference);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_preference, container, false);
        return view;
    }

}
Was it helpful?

Solution

I could not dig out the cause for that particular behavior, but following apparently fixes the issue:

  1. Remove onCreateView().
  2. Add fragment_preference.xml layout directly to the preference.xml.

preference.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <SwitchPreference
        android:defaultValue="true"
        android:key="@string/key_syncing_wifi"
        android:title="123" />
    <SwitchPreference
        android:defaultValue="false"
        android:key="@string/key_syncing_carrier"
        android:title="234" />

    <Preference android:layout="@layout/fragment_preference" />

</PreferenceScreen>

Also, no such behavior is observed with CheckBoxPreference.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top