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