在 MainActivity 的片段中显示 EditText 的值

Display value of EditText in fragment of MainActivity

我需要在 TextView 中显示一个 EditTextpreference(设置 Activity)的值,它位于我的 MainActivity 的片段中。我已经尝试了几种解决方案,我的问题主要是将值保存在所有活动都可以访问的变量中。我听说过两种方法:intent extras 和 SharedPreferences。问题是,在所有教程中,我都看到 TextView 在 MainActivity 中,而不是它的片段,而且我尝试过的代码在那里不起作用。这是我的设置 xml:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <!--CheckBoxPreference
        android:key="example_checkbox"
        android:title="@string/pref_title_social_recommendations"
        android:summary="@string/pref_description_social_recommendations"
        android:defaultValue="true" /-->

    <!-- NOTE: EditTextPreference accepts EditText attributes. -->
    <!-- NOTE: EditTextPreference's summary should be set to its value by the activity code. -->
    <EditTextPreference
        android:key="example_text"
        android:title="@string/pref_title_display_name"
        android:defaultValue="@string/pref_default_display_name"
        android:selectAllOnFocus="true"
        android:inputType="textCapWords"
        android:capitalize="words"
        android:singleLine="true"
        android:maxLines="1"
        android:maxLength="25" />

    <!-- NOTE: Hide buttons to simplify the UI. Users can touch outside the dialog to
         dismiss it. -->
    <!-- NOTE: ListPreference's summary should be set to its value by the activity code. -->
    <ListPreference
        android:key="example_list"
        android:title="@string/pref_title_add_friends_to_messages"
        android:defaultValue="5"
        android:entries="@array/pref_example_list_titles"
        android:entryValues="@array/pref_example_list_values"
        android:negativeButtonText="@null"
        android:positiveButtonText="@null" />

</PreferenceScreen>

这是我的 MainActivity 的片段部分:

public static class PlaceholderFragment extends Fragment {




    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        LayoutInflater lf = getActivity().getLayoutInflater();
        View rootView = lf.inflate(R.layout.fragment_frontpage, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.NameView);
        textView.setText("Test");
        return rootView;
    }

}

所以我的主要目标是创建一个变量,它保存 edittextpreference 的值,然后在

中使用
textView.setText(Variable here);

如何实现?

所有首选项值都存储在具有相应键的默认共享首选项文件中:

     View rootView;
     onCreateView(){
        rootView=inflate(" inflate your view here");
        return rootView;

     }
     onResume(){
           TextView textView=(TextView)rootView.findViewById("your resource id here")
           SharedPreference pref=PreferenceManager.getDefaultSharedPreference(getActivity());
    String text=pref.getString("example_text","")
    textView.setText(text);

     }