我有一个主要 Activity ,它有两个 fragment ,我正在尝试传递一些数据,我想将这些数据附加到下一个 fragment 的编辑文本上已经存在的任何文本上。
具有两个单独选项卡的 Activity :
以下工作正常:
fragment #1:
String y = "TEST 1";
SharedPreferences prefs; // shared preferences
prefs = getActivity().getSharedPreferences("spa", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("someId", y);
editor.commit();
fragment #2:
SharedPreferences prefs; // shared preferences
prefs = getActivity().getSharedPreferences("spa", Context.MODE_PRIVATE);
String someId=prefs.getString("someId","");
showLog.setText(someId + "\n HERE"); //this overwrites the text and is multiline
我想要做的是我希望 showLog 附加到已有的内容之上。
我的showLog如下:
<EditText
android:id="@+id/showLog"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Nothing to display"
android:inputType="textMultiLine"
android:lines="12"
android:paddingLeft="2dip"
android:singleLine="false"
android:textColor="#999999"
android:textSize="14dip"
android:textStyle="normal"
android:gravity="top" />
例如:
showLog
已经开始在文本框中显示“这是一个测试”
当调用 SharedPreference
时,showLog
应显示以下内容:
TEST 1
HERE
THIS IS A TEST
但这并没有发生。我尝试使用 .append()
,但没有任何影响。
最佳答案
我想我明白你现在想要做什么,你可能想尝试:
int start = showLog.getSelectionStart();
int end = showLog.getSelectionEnd();
String toIns = someId + "\n HERE";
showLog.getText().replace(Math.min(start, end), Math.max(start, end), toIns, 0, toIns.length());
从技术上讲,它不是追加,而是用新文本替换字符串的末尾。
编辑:鉴于出现的新问题,以下是我对您的项目的编辑,如果仍有问题,请告诉我。
右侧是我编辑的版本,左侧是原始版本
我对文本所做的可能并不完全是您想要的,所以如果不是,请务必告诉我。
编辑 2:并删除存储的值:
final SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.commit();
编辑3:准确理解您想要做什么后,这里有一种方法可以通过存储添加的最后一次行程并在 TextView 中跟踪您需要的文本来实现。
prefs = getActivity().getSharedPreferences("spa", Context.MODE_PRIVATE);
// Find the string we want
String someId = prefs.getString("someId","");
final Editor editor = prefs.edit();
// To stop a trip being added in onResume etc.
if(someId != prefs.getString("previous-trip", "")){
showLog.setText(someId + prefs.getString("previous", ""));
} else {
// Without this else, we'd have a blank box again
showLog.setText(prefs.getString("previous", ""));
}
// Store the latest trip that was added
editor.putString("previous-trip", someId);
// Store everything that's in the box so far for next time
editor.putString("previous", showLog.getText().toString());
// Commit to the prefs
editor.commit();
关于java - 使用 SharedPreferences 仅 setText() 有效,但append() 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17933480/