除非修改,否则保留编辑文本中的文本

时间:2015-03-27 18:57:41

标签: android android-edittext

我尝试在stackoverflow和android开发者网站上搜索,但是我找不到任何关于如何在用户关闭活动时保持用户在“编辑文本”框中输入文本的方法/命令。

我想要做的是我有一个活动,它在editText框中接受用户的输入,当用户按下后退按钮转到不同的活动,然后当他来的时候(s) )他找到最后输入的文本而不是空白的editText对话框。

如果问到这个问题,请道歉。

3 个答案:

答案 0 :(得分:1)

您必须使用sharedPreferences执行此操作: 像这样保存您的偏好(例如当活动暂停时):

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(YourActivity.this);
prefs.edit().putString("myvalue", myEditText.getText().toString()).apply();

并恢复活动的onCreate方法的值:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(YourActivity.this);
myEditText.setText(prefs.getString("myvalue", ""));

你的活动在最后看起来像这样:

public class MainActivity extends Activity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(this, ShakeService.class));

        EditText myEditText = (EditText)findViewById(R.id.myedittext);
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        myEditText.setText(prefs.getString("myvalue", ""));
    }

    @Override
    protected void onPause()
    {
        super.onPause();

        EditText myEditText = (EditText)findViewById(R.id.myedittext);
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.edit().putString("myvalue", myEditText.getText().toString()).apply();
    }
}

答案 1 :(得分:0)

您需要将其保存在持久存储中。使用SharedPreferences可能是更好的解决方案。

答案 2 :(得分:0)

如果您想这样做,那么当 onbackpress()被调用时,您需要将所有edittext值存储在偏好设置中。

当我们再次参加活动时,请从 onCreate() onResume()中的偏好设置edittext文本。