显示MainActivity片段中EditText的值

时间:2015-03-25 17:34:13

标签: java android android-fragments sharedpreferences preferences

我需要在TextView中显示EditTextpreference(Settings 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);

我如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

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

     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);

     }