創建一個包含一個片段的新活動。在其中插入首選項片段。這裏是我在我的項目中使用的副本。
public class SettingsActivity extends Activity{
public final static String SETTINGS_NATIVE_IGNORE = "pref_native_ignore";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch(id)
{
case android.R.id.home:
onBackPressed();
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
然後將XML它
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:baselineAligned="false"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="...SettingsActivity"
tools:ignore="MergeRootFrame" >
<fragment
android:id="@+id/preferences_fragment"
android:name="...fragment.PreferencesFragment"
tools:layout="@layout/fragment_preferences"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
最後喜好片段
public class PreferencesFragment extends PreferenceFragment {
public PreferencesFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}