問題描述
我有一個登錄屏幕,其中包含 2 個用于用戶名和密碼的 EditText.我的要求是,在方向更改時,EditText 中的輸入數據(如果有)應保持原樣,并且還應繪制新布局.我有 2 個布局 xml 文件 - 一個位于布局文件夾中,另一個位于在布局土地文件夾中.我正在嘗試實現以下兩種方法,但它們都不是完美的:
I have a Login screen which consists of 2 EditTexts for Username and Password. My requirement is that on orientation change , input data(if any) in EditText should remain as it is and a new layout should also be drawn. I have 2 layout xml files- one in layout folder and other in layout-land folder. I am trying to implement following 2 approaches but none of them is perfect:
(1) configChanges:keyboardHidden - 在這種方法中,我不在清單文件的 configChanges 中提供方向".所以我在 onCreate() 和 onConfigurationChanged() 方法中都調用了 setContentView() 方法.它滿足我的兩個要求.布局已更改,EditTexts 中的輸入數據也保持原樣.但它有一個大問題:
(1) configChanges:keyboardHidden - In this approach, I don't provide "orientation" in configChanges in manifest file. So I call setContentView() method in both onCreate() and onConfigurationChanged() methods. It fulfills both my requirements. Layout is changed and input data in EditTexts also remains as it is. But it has a big problem :
當用戶點擊登錄按鈕時,ProgressDialog 會顯示,直到收到服務器響應.現在,如果用戶在 ProgressDialog 運行時旋轉設備,應用程序會崩潰.它顯示一個異常說視圖不能附加到窗口".我嘗試使用 onSaveInstanceState 處理它(在方向更改時會調用它),但應用程序仍然崩潰.
When user clicks on Login button, a ProgressDialog shows until server-response is received. Now if user rotates the device while ProgressDialog is running, app crashes. It shows an Exception saying "View cannot be attached to Window." I have tried to handle it using onSaveInstanceState (which DOES get called on orientation change) but app still crashes.
(2) configChanges:orientation|keyboardHidden - 在這種方法中,我在清單中提供了方向".所以現在我有兩種情況:
(2) configChanges:orientation|keyboardHidden - In this approach, I provide "orientation" in manifest. So now I have 2 scenarios:
(a) 如果我在 onCreate() 和 onConfigurationChanged() 中調用 setContentView() 方法,布局會相應更改,但 EditText 數據會丟失.
(a) If I call setContentView() method in both onCreate() and onConfigurationChanged(), Layout is changed accordingly but EditText data is lost.
(b) 如果我在 onCreate() 中調用 setContentView() 方法,但在 onConfigurationChanged() 中沒有調用,則 EditText 數據不會丟失,但布局也不會相應更改.
(b) If I call setContentView() method in onCreate() , but not in onConfigurationChanged(), then EditText data is not lost but layout also not changes accordingly.
在這種方法中,甚至不會調用 onSaveInstanceState().
And in this approach, onSaveInstanceState() is not even called.
所以我處于一個非常可怕的境地.這個問題有什么解決辦法嗎?請幫忙.提前謝謝.
So I am in a really intimidating situation. Is there any solution to this problem? Please help. Thanx in advance.
推薦答案
在onConfigurationChanged方法中,先在全局變量中獲取兩個編輯文本的數據,然后調用setContentView方法.現在將保存的數據再次設置到編輯文本中.
in onConfigurationChanged method, first get the data of both the edit texts in global variables and then call setContentView method. Now set the saved data again into the edit texts.
這篇關于如何在方向更改時保留 EditText 數據?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!