2

我遇到了这个奇怪的错误:

1 PregerenceFragment 在正常活动中。在片段中有两个 SwitchPreferences。现在一切正常。但是,当我覆盖 onCreateView 方法时,这些开关作为一个开关,意味着它们始终具有相同的状态 - 选中/取消选中一个,另一个做同样的事情。

请问这是知道错误还是我做错了什么?

谢谢

偏好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>

片段布局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>

片段类

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

}
4

1 回答 1

0

我无法找出导致该特定行为的原因,但以下显然解决了该问题:

  1. 删除onCreateView().
  2. 将fragment_preference.xml 布局直接添加到preference.xml。

偏好.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>

此外,没有观察到这样的行为CheckBoxPreference

希望这可以帮助。

于 2013-09-09T20:21:30.583 回答