java安卓:如何在字符串中存储变量的值。通过编码实现xml
要求:我需要将用户Id和密码的值存储为字符串中的字符串值。xml,这实际上是由用户使用的
问题:据我所知,解决方案是使用共享首选项。虽然我使用共享首选项,但这些值不会存储在字符串中。xml
这是我的琴弦。xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Sp</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="id" ></string> <!-- fill in this value from java code, how ? -->
<string name="pwd"></string> <!-- fill in this value from java code, how ? -->
</resources>
布局页面:活动\主。xml
<RelativeLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
xmlns:tools="http://schemas.安卓.com/tools"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent"
tools:context=".MainActivity" >
<EditText
安卓:id="@+id/text"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:layout_alignParentTop="true"
安卓:layout_centerHorizontal="true"
安卓:layout_marginTop="178dp"
安卓:ems="10"
安卓:text="id" >
<requestFocus />
</EditText>
<Button
安卓:id="@+id/button"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:layout_below="@+id/editText1"
安卓:layout_centerHorizontal="true"
安卓:layout_marginTop="44dp"
安卓:text="Send" />
<TextView
安卓:id="@+id/textView1"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:layout_alignBottom="@+id/text"
安卓:layout_alignParentLeft="true"
安卓:layout_marginBottom="40dp"
安卓:layout_marginLeft="22dp"
安卓:text="id" />
</RelativeLayout>
电子文本。爪哇
import 安卓.app.Activity;
import 安卓.content.SharedPreferences;
import 安卓.content.SharedPreferences.Editor;
import 安卓.os.Bundle;
import 安卓.util.Log;
import 安卓.view.View;
import 安卓.widget.Button;
import 安卓.widget.EditText;
public class EdText extends Activity {
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText et=(EditText)findViewById(R.id.text);
Button but = (Button) findViewById(R.id.Button);
but.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0)
{
String s1 = ((EditText)findViewById(R.id.text)).getText().toString().trim();
//Saving your strings
SharedPreferences prefs = getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
Editor editor = PreferenceManager.getDefaultSharedPreferences(Context).edit();
editor.putString("s1", s1.getText().toString());
editor.commit();
//retrieving your strings from preferences
SharedPreferences prefs2 = getSharedPreferences("myPrefsKey",Context.MODE_PRIVATE);
String s12 = prefs.getString("s12", ""); //empty string is the default value
}
});
} }
谢谢你抽出时间
# 1 楼答案
我不知道你从哪里得到这个想法,但它是静态的,因此不能在运行时更改
不过,你可以在这里工作
首先创建一个类并为其添加一个公共静态字符串
例如
设置您的数据或登录
只需在你的应用程序上调用它(活动等)
干杯