簡體   English   中英

在Android中,如何使用Java代碼在string.xml中添加字符串?

[英]How to add a string in string.xml using Java code, in Android?

我已經在我的android應用程序的Java代碼中創建了兩個EditText對象,如下所示

final EditText et1=(EditText)findViewById(R.id.editText1);
final EditText et2=(EditText)findViewById(R.id.editText2);

然后在按鈕的onClick()事件上,該事件稱為參數為-

addStringToXmlFile(et1.getText(),et2.getText());

現在在下面這種方法的定義中,我寫了

private void addStringToXmlFile(Editable editable1,Editable editable2){
        String s1=new String();
        s1=editable1.toString();

        String s2=new String();
        s2=editable2.toString();
}

問題是,現在我想使用這兩個String對象s1,s2,在數據庫的res/values/Strings.xml文件中創建兩個條目,並且我不知道該怎么做。

請進一步指導我。

這是不可能的-應用程序的apk(包括其資源)不能在運行時更改。 我不確定所有原因,但我可以想到的一件顯而易見的事情是R.java需要包含對String的引用才能訪問它,並且該文件是由編譯器生成的創建APK時。

如果您需要在會話之間保留String,則應研究使用Android提供的幾種數據存儲機制之一,例如SharedPreferences

看一下使用SharedPreferences來存儲您的字符串值。

//Saving your strings
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString("s1", s1);
editor.putString("s2", s2);
editor.commit();

//retrieving your strings from preferences
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
String s1 = prefs.getString("s1", ""); //empty string is the default value
String s2 = prefs.getString("s2", ""); //empty string is the default value

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM