我试图将偏好设置加载到我的片段中,这有效,但我似乎找不到改变布局的方法。现在我有这个问题:
这是我的代码:
public class SettingsFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
//getFragmentManager().beginTransaction().add(android.R.id.content, new MyPreferenceFragment()).commit();
getFragmentManager().beginTransaction().add(android.R.id.content, new MyPreferenceFragment()).commit();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_settings, container, false);
}
public static class MyPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
在这个stackoverflow上,他们正在做我想要实现的目标,除了setContentView不能在片段How to add a button to PreferenceScreen
中工作这是我的preference.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:key="username"
android:summary="Please provide your username"
android:title="Your Name">
</EditTextPreference>
<CheckBoxPreference
android:defaultValue="false"
android:key="applicationUpdates"
android:summary="This option if selected will allow the application to check for latest versions."
android:title="Application Updates" />
<ListPreference
android:defaultValue="1"
android:entries="@array/listArray"
android:entryValues="@array/listValues"
android:key="downloadType"
android:summary="Select the kind of data that you would like to download"
android:title="Download Details" />
我的片段xml
<FrameLayout 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"
tools:context="nl.shacklez.mijnreceptenofficialv1.SettingsFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
答案 0 :(得分:1)
这可以解决您的问题
您添加 Fragment
尝试替换Fragment
喜欢替换
getFragmentManager().beginTransaction().add(android.R.id.content, new MyPreferenceFragment()).commit();
通过
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
答案 1 :(得分:0)
您将片段设置为视图两次。您在onCreateView中设置它 - 它实例化一个新的preferenceFragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_settings, container, false);
}
然后你正在打电话
getFragmentManager().beginTransaction().add(android.R.id.content, new MyPreferenceFragment()).commit();
再次调用您的preferenceFragment的onCreate,因此您将片段绑定两次。