使用SharedPreferences在片段中显示MainActivity中保存的EditText



我正在将EditText保存到SharedPreferences中,但在Fragment中看不到保存的文本。有人能告诉我我做错了什么吗?顺便说一句,我在apk中使用了SharedPreferences。

这是我在MainActivity中保存数据的代码。

public static final String Save_Search = "Save_Search";
public EditText searchPlugin;
public String textForSearch;

searchPlugin = findViewById(R.id.etSearch);

public void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences(Save_Search, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(editText, searchPlugin.getText().toString());  editor.putString(Save_Search, searchPlugin.getText().toString());
Log.d("Test", searchPlugin.getText().toString());
//This is saving me the typed text.
}
public void updateView() {
searchPlugin.setText(textForSearch);
}

这是EditText 的布局

<EditText android:id="@+id/etSearch" android:imeOptions="actionGo|flagNoExtractUi" style="@style/SearchEditText.MainSearch" />

这是碎片

public class FragmentHistory extends Fragment {
View paramView;
TextView textView;
public FragmentHistory() {
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
paramView = inflater.inflate(R.layout.history_item, container, false);
textView = paramView.findViewById(R.id.tvHistoryName);
SharedPreferences pref = getActivity().getPreferences(Context.MODE_PRIVATE);
String text = pref.getString("Save_Search", "");
textView.setText(text);
return paramView;
}

}

这是历史布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:background="@drawable/selector_btn_home"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:id="@id/ivHistory" style="@style/ivHistory" />
<TextView android:id="@id/tvHistoryName" android:layout_height="38dp" style="@style/TextViewQuery"/>
<ImageView android:id="@id/imgViewSetQuery" style="@style/ImageViewSetQuery" />
<TextView android:textSize="@dimen/search_font" android:textColor="@android:color/white"
android:gravity="center" android:id="@id/btnDelete" android:background="@color/red" android:paddingLeft="5.0dip"
android:paddingRight="5.0dip" android:visibility="gone" android:longClickable="false"
android:layout_width="wrap_content" android:layout_height="fill_parent" android:text="@string/Delete" />
</LinearLayout>

您试图通过"save_Search"键保存数据,但您正在保存数据在键"editText"下

替换此行:

editor.putString(editText, searchPlugin.getText().toString());

使用此行

editor.putString(Save_Search, searchPlugin.getText().toString());

替换:

SharedPreferences pref = getActivity().getPreferences(Context.MODE_PRIVATE);

带有:

SharedPreferences preferences = this.getActivity().getSharedPreferences("Save_Search", Context.MODE_PRIVATE);

在你的碎片中

相关内容

  • 没有找到相关文章

最新更新