[英]How to use SharedPreferences to save the text entered in edittext and display it in TextView in another Activity
[英]Save EditText and TextView data and display it in another activity
我正在开发一个将两个数字相加的应用程序。 用户通过EditText提供数字,结果通过TextView显示。 我想要做的是保存用户输入的数字值和通过按钮保存的结果(在用户需要时随时查看它们),并在另一个活动的布局中显示它们(没有EditText)。 请注意,用户将可以随时查看保存的结果。
希望您能够帮助我。 非常感谢。
从您的问题中我了解 ::
您的第一个editText1
具有value1
您的第二个editText2
具有value2
textView1
的结果为value1
和value2
解决方案 ::从views
获取值,并使用intents
在activities
之间传递数据
代码 ::
In your current Activity, create a new Intent:
OnCreate()
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("editText1",editText1.getText());
i.putExtra("editText2",editText2.getText());
i.putExtra("textView1",textView1.getText());
startActivity(i);
Then in the new Activity, retrieve those values:
OnCreate()
Bundle extras = getIntent().getExtras();
if (extras != null) {
String editText1= extras.getString("editText1");
String editText2= extras.getString("editText2");
String textView1= extras.getString("textView1");
}
使用变量editText1
, editText2
和textView1
在第二活动为u希望的值设置为任何的意见
希望能帮助您,如果您在调试中遇到任何问题,请告诉我
利用这样的SharedPreferences
:
SharedPreferences sp= getSharedPreferences("ttt", 0);
SharedPreferences.Editor editor = sp.edit();
String etValue=(EditText)findViewById(R.id.yourEditTextId).getText().toString();
String tvValue=(TextView)findViewById(R.id.yourTextView).getText().toString();
editor.putString("etValue", etValue);
editor.putString("tvValue", tvValue);
editor.commit();
// in anywhere user wants
SharedPreferences settings = getSharedPreferences("ttt", 0);
String yourEditTextValue=settings.getString("etValie", "");
String yourTextViewValue=settings.getString("tvValie", "");
有多种方法可以实现:
方法1:使用静态类的setter和getter方法:
创建静态类并从第一个活动中设置值并从第二个活动中获取值
方法2:
通过意图发布您的价值观
方法3:
使用数据库存储一项活动的数据并从另一项活动获取数据
方法4:
使用共享首选项
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.