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

Android Studio应用中EditButton编辑内容退出后无法保存求助

Hey there! Let's troubleshoot why your edited text isn't saving after closing the window in your Android app. This is a super common pitfall, and it almost always comes down to not persisting the changes properly or failing to load them back later. Here are the most likely fixes, with code examples:

1. You're not saving the edited text when the user finishes editing

The biggest mistake here is only modifying the EditText's in-memory content without writing it to a persistent storage (like SharedPreferences, Room Database, or a local file). You need to trigger a save action when the user confirms their changes—either via a "Save" button, or when they press the "Done" key on the keyboard.

Example with a Save Button + SharedPreferences

// In your Activity/Fragment
val editText = findViewById<EditText>(R.id.your_edit_text)
val saveButton = findViewById<Button>(R.id.save_btn)

saveButton.setOnClickListener {
    val updatedText = editText.text.toString().trim()
    
    // Save to SharedPreferences (simple key-value storage)
    val prefs = getSharedPreferences("AppSettings", MODE_PRIVATE)
    prefs.edit()
        .putString("saved_content", updatedText)
        .apply() // Use apply() for async save, commit() for sync (not recommended for UI thread)
    
    // Close the window
    finish() // Or dismiss the dialog if you're using one
}

Example with Keyboard "Done" Action

If you want to save when the user presses Done on the keyboard:

editText.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        val updatedText = editText.text.toString().trim()
        // Same save logic as above
        val prefs = getSharedPreferences("AppSettings", MODE_PRIVATE)
        prefs.edit().putString("saved_content", updatedText).apply()
        
        // Hide keyboard and close window
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(editText.windowToken, 0)
        finish()
        return@setOnEditorActionListener true
    }
    false
}

2. You're not loading the saved text when the window opens

Even if you save the text correctly, if you don't load it back into the EditText when the Activity/Fragment/Dialog starts, it'll look like nothing was saved. Always fetch the persisted content during initialization.

Example: Load saved text in onCreate()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.your_layout)
    
    val editText = findViewById<EditText>(R.id.your_edit_text)
    val prefs = getSharedPreferences("AppSettings", MODE_PRIVATE)
    
    // Load the saved text, default to empty string if nothing exists
    val savedText = prefs.getString("saved_content", "")
    editText.setText(savedText)
}

3. If you're using a Dialog, you're not capturing the text correctly

If your EditText is inside an AlertDialog, don't rely on the dialog's close event to get the text. Always grab the text directly when the user taps the "Save" button in the dialog.

Example: Dialog with EditText save logic

val dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_edit, null)
val dialogEditText = dialogView.findViewById<EditText>(R.id.dialog_edit_text)

// First, load the existing saved text into the dialog's EditText
val prefs = getSharedPreferences("AppSettings", MODE_PRIVATE)
val savedText = prefs.getString("saved_content", "")
dialogEditText.setText(savedText)

AlertDialog.Builder(this)
    .setTitle("Edit Content")
    .setView(dialogView)
    .setPositiveButton("Save") { _, _ ->
        val updatedText = dialogEditText.text.toString().trim()
        // Save the text
        prefs.edit().putString("saved_content", updatedText).apply()
    }
    .setNegativeButton("Cancel", null)
    .show()

4. Advanced: Using Room Database for structured data

If you're dealing with more complex data (like multiple entries), use Room instead of SharedPreferences. The core logic stays the same: save when edits are confirmed, load when the screen initializes.

Quick Room Example

// Your DAO interface
@Dao
interface NoteDao {
    @Update
    suspend fun updateNote(note: Note)
    
    @Query("SELECT * FROM notes WHERE id = :noteId")
    suspend fun getNoteById(noteId: Int): Note?
}

// In your ViewModel or Activity
viewModelScope.launch {
    val note = noteDao.getNoteById(1)
    note?.let {
        editText.setText(it.content)
    }
}

saveButton.setOnClickListener {
    viewModelScope.launch {
        val updatedNote = note?.copy(content = editText.text.toString().trim())
        updatedNote?.let { noteDao.updateNote(it) }
        finish()
    }
}

Final Check

Double-check these two things:

  • Are you persisting the edited text to a storage that survives app restarts/window closures? (In-memory variables get lost when the window closes!)
  • Are you loading that persisted text back into the EditText every time the window opens?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:31:37