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

如何在Xamarin应用中保存TextView内容,重启后仍可显示?

当然可以实现,用SharedPreferences就能搞定

SharedPreferences是Android官方提供的轻量键值对存储方案,正好适合保存这种简单的文本内容,下面直接给你改好的代码:

修改后的完整代码

namespace App11
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        EditText edt;
        TextView res;
        // 定义SharedPreferences实例
        ISharedPreferences prefs;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.activity_main);

            edt = FindViewById<EditText>(Resource.Id.appCompatEditText1);
            Button btn = FindViewById<Button>(Resource.Id.button1);
            res = FindViewById<TextView>(Resource.Id.textView10);

            // 获取SharedPreferences实例,名字自定义,模式设为私有
            prefs = GetSharedPreferences("MyAppPrefs", FileCreationMode.Private);
            // 启动时读取保存的值,无保存内容时用空字符串
            string savedText = prefs.GetString("SavedTextViewValue", string.Empty);
            res.Text = savedText;

            btn.Click += Btn_Click;
        }

        private void Btn_Click(object sender, System.EventArgs e)
        {
            string s = edt.Text.ToString();
            res.Text = s;

            // 点击按钮时写入内容到SharedPreferences
            ISharedPreferencesEditor editor = prefs.Edit();
            editor.PutString("SavedTextViewValue", s);
            editor.Apply(); // 异步提交,避免阻塞UI线程
        }

        // 处理Xamarin.Essentials权限请求(原代码需补充的必要方法)
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}

关键说明

  • 初始化SharedPreferences:通过GetSharedPreferences创建私有存储文件,仅当前应用可访问
  • 读取数据:在OnCreate阶段调用GetString获取保存值,第二个参数为无数据时的默认值
  • 保存数据:点击按钮时通过编辑器写入内容,用Apply()异步提交,比同步的Commit()更适合UI场景

这样重启应用后,TextView就会自动加载上次保存的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:50:53