【问题标题】:Save attributes when close activity关闭活动时保存属性
【发布时间】:2015-11-20 11:40:18
【问题描述】:

我有产品列表的活动,我将属性传递给购物篮活动

产品列表活动中的代码:

    zakazat.Click += delegate 
        {
            var intent = new Intent(this, typeof(CartActivity));
            intent.PutExtra ("title", (string)(firstitem ["post_title"]));
            intent.PutExtra ("price", (string)(firstitem ["price"] + " грн"));
            intent.PutExtra ("weight", (string)(firstitem ["weight"] + "г"));
            StartActivity(intent);

在购物篮中接收产品:

public  void Display (){

        LinearLayout display = FindViewById<LinearLayout> (Resource.Id.product1);         
        TextView productname = FindViewById<TextView> (Resource.Id.posttittle1);
        TextView price = FindViewById<TextView> (Resource.Id.price1);
        TextView weight = FindViewById<TextView> (Resource.Id.weight1);



        price.Text = Intent.GetStringExtra("price");

        productname.Text = Intent.GetStringExtra("title");

        if (productname.Text == Intent.GetStringExtra ("title")) {
            display.Visibility = ViewStates.Visible;
        } 
        else {
            display.Visibility = ViewStates.Gone;
        }

        weight.Text = Intent.GetStringExtra("weight");


    }

我有两个问题,当我改变活动时如何保存这个属性以及如何在后台传递这个属性?

有什么建议可以让我实现这一点吗?

【问题讨论】:

  • 不。我意识到转移到另一个活动。正如我在@ZahanSafallwa 帖子末尾所写的那样,我需要在活动中保存属性
  • 保存属性是什么意思?将数据存储到文件之类的东西???
  • 切换活动时保存属性,再次打开时看到。 @ZahanSafallwa

标签: c# android xamarin


【解决方案1】:

你可以做两件事。

  1. 保存到 SQLite
  2. 保存到 SharedPreferences。

如果您不想以这种速度依赖 SQLite,那么您将需要使用选项 #2,因为它更容易实施。

我们如何使用 SharedPreferences?

首先,你必须在你的类上声明一个 ISharedPreference。

public class YourActivity : Activity 
{ 
    private ISharedPreferences prefs;
}

接下来,您需要在 onCreate 方法中初始化 prefs 变量。

prefs = PreferenceManager.GetDefaultSharedPreferences(this);

然后你可以像这样将你的 Intent extras 写到首选项中:

ISharedPreferencesEditor editor = prefs.Edit ();
editor.PutString ("price", Intent.GetStringExtra("price"));
editor.PutString ("title", Intent.GetStringExtra("title"));
editor.PutString ("weight", Intent.GetStringExtra("weight"));
editor.Apply ();

写好首选项后,您想访问里面的数据。你必须这样做:

string price = prefs.GetString("price", "0"); 
string title = prefs.GetString ("title" , ""); 
string weight = prefs.GetString ("weight" , ""); 
//second argument in GetString(arg1, arg2) means a default value given to the variable if it is null

这样,即使关闭 Activity,您仍然可以检索 SharedPreferences 值。

请注意,您需要添加 using Android.Preferences; 才能使用首选项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    相关资源
    最近更新 更多