要求:我需要将用户 ID 和密码的值作为字符串值存储在 String.xml 中,这些值确实由用户获取。
问题:据我所知,解决方案是使用共享首选项。虽然我使用 Shared Preferences ,但值不会存储在 String.xml
这是我的 Strings.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>
布局页面:activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<EditText
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="178dp"
android:ems="10"
android:text="id" >
<requestFocus />
</EditText>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="44dp"
android:text="Send" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/text"
android:layout_alignParentLeft="true"
android:layout_marginBottom="40dp"
android:layout_marginLeft="22dp"
android:text="id" />
</RelativeLayout>
EdText.java
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.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
}
});
} }
感谢您的时间