0
我下面這個頁面https://developer.android.com/guide/topics/ui/settings.html我是否必須製作新的活動才能使用設置片段?
這裏偏好片段的解決方案是使用的代碼:
public static class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
...
}
public class SettingsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
}
該解決方案的工作,但我這樣做之前,我嘗試不同的東西。
起初,我嘗試在不使用SettingsActivity的情況下打開設置。我想與設置片段切換我的主要片段在我的主要活動本身(這個代碼是我的MainActivity文件內):
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.container, new SettingsFragment());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
return true;
}
return super.onOptionsItemSelected(item);
}
這R.id.container是的FrameLayout在我activity_main.xml中
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame" >
</FrameLayout>
這種方法似乎並不奏效,爲什麼?由於當前片段未被替換,所以設置片段經過當前片段。
如果我選擇使用菜單片段進行新的活動,性能會受到怎樣的懲罰?
謝謝你的幫助。
我試過這個解決方案,但我的設置片段仍然與我的主要片段重疊。 – MrBuggy