[英]Via rotate orientation change layout without reload OnCreate()
我在不同的文件夾中有3個布局:
1. layout / HomeLayout.axml (其中layout是布局的文件夾,而HomeLayout.axml是全局axml文件)。
2. layout-large-port / HomeLayout.amxl (其中layout-large-port是用於大(顯示尺寸)肖像的文件夾,而HomeLayout.axml是axml文件)。
3. layout-large-land / HomeLayout.axml (其中layout-large-land是用於顯示大(顯示尺寸)景觀的文件夾,而HomeLayout.axml是axml文件)。
在此活動中,我得到的ListView了一些數據,當我從縱向到橫向旋轉我的電話,我需要保存所有我maked在人像模式(在列表視圖eachrow有像按鈕 / TextView中和等不同的東西),並顯示在景觀 。
那么,目前該怎么辦。 在HomeActivity上,我聲明了這一點:
ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation
該代碼段效果很好,但存在一個大問題:旋轉(從Portrait到Landscape )后仍保持布局Portrait。 我該如何解決?
我也試圖重寫方法OnConfigurationChanged
:
public override void OnConfigurationChanged(Android.Content.Res.Configuration newConfig)
{
base.OnConfigurationChanged (newConfig);
if(newConfig.Orientation == Android.Content.Res.Orientation.Landscape)
{
SetContentView(Resource.Layout.ProductsLayout); //system understand that now is Landscape and put correct layout;
}
else
{
SetContentView(Resource.Layout.ProductsLayout); //same here
}
所以此方法無濟於事,因為當我旋轉手機時,布局設置正確但沒有數據(列表視圖為空),此后,當我嘗試從橫向返回到人像時 ,布局設置正確但為空清單。
有什么建議么?
PS對不起,我的英文!
更改配置后,Android會完全破壞並重新創建您的活動; 該活動中的所有視圖及其持有的數據也將被丟棄。
從Android文檔 :
警告:每次用戶旋轉屏幕時,您的活動都會被破壞並重新創建。 當屏幕改變方向時,系統將銷毀並重新創建前台活動,因為屏幕配置已更改,並且您的活動可能需要加載替代資源(例如布局)。
在配置更改之間持久保存數據的標准機制是使用Activity
的OnSaveInstanceState
回調保存視圖數據,然后使用通過OnCreate
回調提供的捆綁包還原數據。
這是一個大概的例子:
public class MainActivity : Activity
{
public const string ARG_LIST_STATE = "list_state";
ListView _listView;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
if (bundle != null) {
// Existing data to restore!
if (bundle.ContainsKey (ARG_LIST_STATE)) {
var listState = bundle.GetStringArray (ARG_LIST_STATE);
// TODO: Restore state into list view.
}
}
}
protected override void OnSaveInstanceState (Bundle outState)
{
string[] listState= new string[5]; // TODO: Grab data from the list view and serialize it into the outState
outState.PutStringArray(ARG_LIST_STATE, listState);
base.OnSaveInstanceState (outState);
}
}
Xamarin 在此提供了另一個示例。
我強烈建議您查看活動生命周期文檔,以便更好地了解Android如何管理活動。
解決方案是(對我來說)為肖像做出可接受的設計,這是因為它與橫向模式沒有區別(僅使用諸如sum_weight等的機制)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.