未显示偏好 - 偏好片段

Preference Not Displayed - Preference Fragment

我正在尝试创建一个设置Activity 并使用一个扩展 PreferenceFragment 的片段来实现此目的。我的 Activity 正在显示,而首选项不是 。

SettingsActivity.java

public class SettingsActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment())
                .commit();

}

SettingsFragment.java

public  class SettingsFragment extends PreferenceFragment {



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.pref);
    Toast ts = Toast.makeText(getActivity(),"Working",Toast.LENGTH_SHORT);
    ts.show();
}

}

pref.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen  xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
    android:key="@string/prefsync"
    android:title="@string/pre_name"
    android:summary="@string/summary"
    android:defaultValue="true" />

 </PreferenceScreen>

我在测试 1st Moto X phone 时遇到了同样的问题。这就是我最终所做的,现在工作正常:我在添加片段之前向 SettingsActivity 添加了一个空布局。

public class SettingsActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState ){
        super.onCreate(savedInstanceState);

        //Need to set layout to blank if we want to add fragments to it.
        setContentView(R.layout.activity_settings);

        getFragmentManager()
                .beginTransaction()
                .add( android.R.id.content, new SettingsFragment() )
                .commit();
    }

}

为布局加载的 xml 文件是 Android Studio 通常创建的空白布局。看起来像这样。

<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.wordscroll.wordscroll.SettingsActivity">

</RelativeLayout>