2

Мне нужно отобразить значение EditTextpreference (Activity Activity) в TextView, которое находится в фрагменте моей MainActivity. Я уже пробовал несколько решений, моя проблема в основном заключается в сохранении значения в переменной, доступной для всех видов деятельности. Я слышал о двух путях: намерениях и SharedPreferences. Проблема в том, что во всех обучающих программах я видел, что TextView находится в MainActivity, а не в его фрагменте, и код, который я пытался, не работает там. Вот мои настройки XML:Отображать значение EditText в фрагменте MainActivity

<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

Все значения предпочтения сохраняются в стандартных общие файлы настроек с соответствующими ключами:

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

    } 
+0

код, кажется, работает, но часть с GetString выдает ошибку: не может разрешить символ example_text. Может быть, я каким-то образом должен определить это или создать переменную locar? –

+0

Попробуйте «example_text» - это ключ, который вы указали в качестве ключа к вашему текстовому предпочтению редактирования. – krishna

+0

EDIT: да, это работает. Еще одно расширение: текст изменяется только при загрузке apk, это означает, что если я перейду к активности настроек, измените значение, а затем вернитесь к mainactivity, он не изменится сразу. Не могли бы вы мне помочь? –

 Смежные вопросы

  • Нет связанных вопросов^_^