[英]Save the state of my Activity xamarin.android
當有人關閉應用程序時,我想保存此活動的狀態。 它只包含一個 ListActivity simplelistitemchecked ...
namespace XamarinScanner
{
[Activity(Label = "@string/scanHistory", ScreenOrientation = ScreenOrientation.Portrait)]
public class ScanHistoryActivity : ListActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
var codes = Intent.Extras.GetStringArrayList("Codes");
codes.ToList();
ListAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItemChecked, codes);
ListView lv = FindViewById<ListView>(Android.Resource.Id.List);
lv.ChoiceMode = ChoiceMode.Multiple;
foreach (var c in codes)
{
if (c.Contains("Success"))
{
int position = codes.IndexOf(c);
lv.SetItemChecked(position, true);
}
}
}
}
}
這是我為主要活動保存狀態的地方,它似乎在后台保存我的列表活動和主要活動的數據。 我想我只需要在應用程序被銷毀時做同樣的事情..
protected override void OnSaveInstanceState(Bundle outState)'
{
outState.PutStringArrayList("Codes", _codes.ToArray());
base.OnSaveInstanceState(outState);
}
protected override void OnCreate(Bundle bundle)
{
Url = "http://10.0.0.103:4321/Scan";
if (bundle != null)
{
var c = bundle.GetStringArrayList("Codes");
instance state");
}
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);`
用戶關閉應用程序是什么意思? 你的意思是當他關閉它一會兒然后再次打開它或者當應用程序完全關閉時?
如果您的意思是第二次,您應該使用 OnDestroy 來“保存”狀態並在下次加載 OnCreate 。 您必須手動創建保存和加載過程(使用數據庫?SharedPreferences?這取決於您)
另請在此處查看活動生命周期。
還總是發布您迄今為止嘗試過的內容,但它不想要以及您期望的確切結果
在 OnDestroy 上存儲值的一種簡單方法是使用 SharedPreferences:
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (Application.Context);
ISharedPreferencesEditor editor = prefs.Edit ();
editor.PutBoolean ("keyName", _bool);
// editor.Commit(); // applies changes synchronously on older APIs
editor.Apply(); // applies changes asynchronously on newer APIs
使用以下方法訪問保存的值:
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (Application.Context);
_bool = prefs.GetBoolean ("keyName");
_int = prefs.GetInt ("keyName");
_string = prefs.GetString ("keyName");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.