You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中能否用EditText修改strings.xml里的字符串值?

Can I modify strings.xml content via EditText in Android Studio?

Hey there! Let’s tackle this question straight away—you can’t directly edit the strings.xml resource file at runtime using an EditText, and here’s why:

strings.xml is a static resource file that gets compiled into your APK during the build process. Once your app is installed on a device, this file is part of the signed APK package, which is read-only. Any attempt to modify it directly will fail (and likely cause crashes or security issues, since altering signed app resources breaks the app’s integrity).

But don’t worry—there are straightforward workarounds depending on what you’re trying to achieve:

Option 1: Dynamically update UI text (no persistence)

If you just want to display the text from EditText in place of the original "GOOD" string in your UI, you don’t need to touch strings.xml at all. Just update the target view’s text directly when the user inputs content:

// In your Activity/Fragment
val editText = findViewById<EditText>(R.id.your_edit_text)
val displayTextView = findViewById<TextView>(R.id.your_display_text_view)

// Set a listener to update the text when the user types
editText.addTextChangedListener(object : TextWatcher {
    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        // Update the display text with EditText's content
        displayTextView.text = s ?: getString(R.string.OK)
    }
    override fun afterTextChanged(s: Editable?) {}
})

Option 2: Persist the modified text (retain after app restarts)

If you want the modified text to stay even after the app closes and reopens, use SharedPreferences to store the user’s input, then load it instead of the default string resource:

Save the input to SharedPreferences:

val sharedPref = getSharedPreferences("AppPrefs", Context.MODE_PRIVATE)
val editor = sharedPref.edit()
editor.putString("custom_ok_text", editText.text.toString())
editor.apply()

Load the saved text when initializing your UI:

val sharedPref = getSharedPreferences("AppPrefs", Context.MODE_PRIVATE)
val customText = sharedPref.getString("custom_ok_text", getString(R.string.OK))
displayTextView.text = customText

This way, the first time the app runs, it uses the default "GOOD" from strings.xml. After the user enters a new value (like "BAD"), that value is saved and used in future sessions.

Just remember: never try to modify the original strings.xml file at runtime—it’s not supported and will cause more problems than it solves.

内容的提问来源于stack exchange,提问作者Hanafis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:05:09