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

Android开发咨询:保存EditText添加的文本及GridView换ListView可行性

嗨Gustav,作为Android新手能想到这些优化点超棒的!我来帮你一一解答你的两个问题:


问题1:保存EditText输入的文本完全可行!

你有好几种方式可以实现,根据你的需求选就行:

  • 临时存储(适合单次会话):如果只是想在App打开期间保存,可以把文本存在ViewModel或者自定义的Application类里,这样在不同Activity间也能轻松获取。
  • 持久化存储(重启App也能保留):
    • SharedPreferences:适合存储少量键值对数据,比如单个或少量文本,代码示例如下:
      // 保存文本到SharedPreferences
      val sharedPref = getSharedPreferences("MyPrefs", MODE_PRIVATE)
      with(sharedPref.edit()) {
          putString("saved_text", editText.text.toString())
          apply()
      }
      
      // 读取保存的文本
      val savedText = sharedPref.getString("saved_text", "")
      
    • SQLite数据库:如果需要保存多条输入的文本,后续要做增删改查,就可以用SQLite(或者用Room框架,更简单易上手)。

问题2:完全可以把GridView替换成ListView,而且ListView完全支持你的需求!

GridView是网格布局(多列展示),ListView是垂直单列列表,两者都是Android常用的列表控件,都能用来展示你输入的文本,实现逻辑很相似,只是布局样式不同。

给你一个简单的ListView实现步骤:

  1. 在第二个Activity的布局文件里替换GridView为ListView:
    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    
  2. 在第二个Activity的代码里,接收第一个Activity传过来的文本,然后用Adapter绑定到ListView:
    class SecondActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_second)
    
            // 获取从第一个Activity传过来的文本
            val inputText = intent.getStringExtra("INPUT_TEXT") ?: ""
    
            // 假设你要保存多条文本,可以用一个MutableList来存
            val textList = mutableListOf(inputText)
            // 如果有之前保存的历史文本,也可以一起加进来
    
            // 创建Adapter并绑定到ListView
            val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, textList)
            findViewById<ListView>(R.id.listView).adapter = adapter
        }
    }
    

如果后续你想添加更多文本,只需要把新文本加到textList里,然后调用adapter.notifyDataSetChanged()就能更新ListView的展示啦。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:06:31