好的...我终于解决了! :)
保存活动状态而不是阻止活动重新加载,乍一看似乎有点棘手,但实际上非常简单,它是此类情况的最佳解决方案。
就我而言,我有一个 ListView,它从 Internet 中填充项目,存储在自定义列表适配器中。如果更改了设备方向,则重新加载了活动,ListView 也是如此,并且我丢失了所有数据。
我需要做的就是重写OnRetainNonConfigurationInstance 方法。
这是一个如何做的快速示例。
首先,我们需要一个可以处理我们所有东西的类。
这是我们需要保存的所有内容的包装器:
public class MainListAdapterWrapper : Java.Lang.Object
{
public Android.Widget.IListAdapter Adapter { get; set; }
public int Position { get; set; }
public List<YourObject> Items { get; set; }
}
在我们的活动中,我们需要保存变量,来存储所有数据:
ListView _listView; //Our ListView
List<YourObject> _yourObjectList; //Our items collection
MainListAdapterWrapper _listBackup; //The instance of the saving state wrapper
MainListAdapter _mListAdapter; //Adapter itself
然后,我们在活动中重写OnRetainNonConfigurationInstance 方法:
public override Java.Lang.Object OnRetainNonConfigurationInstance()
{
base.OnRetainNonConfigurationInstance();
var adapterWrapper = new MainListAdapterWrapper();
adapterWrapper.Position = this._mListAdapter.CurrentPosition; //I'll explain later from where this came from
adapterWrapper.Adapter = this._listView.Adapter;
adapterWrapper.Items = this._yourObjectList;
return adapterWrapper;
}
最后阶段是在OnCreate方法中加载保存的状态:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.list);
this._listView = FindViewById<ListView>(Resource.Id.listView);
if (LastNonConfigurationInstance != null)
{
this._listBackup = LastNonConfigurationInstance as MainListAdapterWrapper;
this._yourObjectList = this._listBackup.Items;
this._mListAdapter = this._listBackup.Adapter as MainListAdapter;
this._listView.Adapter = this._mListAdapter;
//Scrolling to the last position
if(this._listBackup.Position > 0)
this._listView.SetSelection(this._listBackup.Position);
}
else
{
this._listBackup = new MainListAdapterWrapper();
//Here is the regular loading routine
}
}
关于this._mListAdapter.CurrentPosition... 在我的MainListAdapter 中,我添加了这个属性:
public int CurrentPosition { get; set; }
在 `GetView' 方法中,我做到了:
this.CurrentPosition = position - 2;
附言
您不必完全按照我在此处显示的那样实现。在这段代码中,我保存了很多变量,并在 OnCreate 方法中创建了所有例程 - 这是错误的。我这样做只是为了展示它是如何实现的。