Android手機轉向時,activity其實是經過pause、create、resume,所以所有暫時資訊都會被清掉,所以設計師必須在pause時對使用者資訊進行暫存,並在resume的地方回復。這是一般程式設計師的狀況,不過有些資訊是沒辦法回存的,例如一個webview,裡面有些form正填到一半,結果使用者觸發orientation時,就算webview 重新loadurl同一個網址,form也是空白的。再例如youtube play到一半時轉向,重新loadurl則必須重新開始。

 

這類問題有兩個解決方案

1.禁止轉向:這是最方便卻是最鴕鳥的作法,禁止使用者轉向自然就沒有轉向後重新讀取的問題。

透過以下語法

Dim p As Phone

p.SetScreenOrientation(0)  '固定橫向

p.SetScreenOrientation(1)  '固定直立

p.SetScreenOrientation(-1) 'Auto

 

詳細參閱b4a討論區:http://www.b4x.com/android/forum/threads/orientation-setting-test.21056/ 

 Orient.Initialize ("Orient") 

 Orient.AddSingleLine2("-1 = Auto (Sensor)",-1) 

 Orient.AddSingleLine2(" 0 = Landscape - Set",0) 

 Orient.AddSingleLine2(" 1 = Portrait - Set",1) 

 Orient.AddSingleLine2(" 6 = Landscape - Sensor",6) 

 Orient.AddSingleLine2(" 7 = Portrait - Sensor",7)

 Orient.AddSingleLine2(" 8 = Reversed Landscape - Set",8)

 Orient.AddSingleLine2(" 9 = Reversed Portrait - Set",9)

 

 

2.修改AndroidManifest.xml:使用語法『android:configChanges="orientation|keyboardHidden|screenSize"』

這樣activity就不會在轉向時重新create。不過產生的問題卻是,整個activity依然保持原來大小,也就是說橫向轉直,他還是橫的,下半部是黑的,如果直轉橫,就會右邊是黑色一塊。

所以接下來就要處理轉向後的relayout的問題,B4A反而比較麻煩,必須使用IME.HeightChanged這個弔詭的方法。

這個想法就是:當轉向時,會改變IME的預設高度,因此我在IME.HeightChanged的event這裡做relayout,不過這樣的話,原始的Layout的Designer就幾乎沒使用的餘地了。

 

詳細參閱b4a討論區:http://www.b4x.com/android/forum/threads/persist-webview-through-orientation-change.37511/

 

Sub Globals

   Private ime1 As IME

   Private WebView1 As WebView

   Private ActivityParent As JavaObject

End Sub

 

Sub Activity_Create(FirstTime As Boolean)

   WebView1.Initialize("WebView1")

   Activity.AddView(WebView1, 0, 0, 100%x, 100%y)

   ime1.Initialize("ime1")

   ime1.AddHeightChangedEvent

   WebView1.LoadUrl("http://www.google.com")

   Dim jo As JavaObject = Activity

   jo.RunMethodJO("getContext", Null).RunMethodJO("getWindow", Null).RunMethod("setSoftInputMode", _

     Array As Object(0x20))

   ActivityParent = jo.RunMethodJO("getParent", Null)

End Sub

Sub IME1_HeightChanged (NewHeight As Int, OldHeight As Int)

   CallSubDelayed(Me, "AfterChange")

End Sub

 

Sub AfterChange

   Dim ajo As Panel = Activity

   Dim width As Int = ActivityParent.RunMethod("getMeasuredWidth", Null)

   Dim height As Int = ActivityParent.RunMethod("getMeasuredHeight", Null)

   If width = 0 OR height = 0 Then Return

   ajo.Width = width 'update the "activity" width and height

   ajo.Height = height

   WebView1.Width = width

   WebView1.Height = height

End Sub

arrow
arrow
    全站熱搜

    夜市 小霸王 發表在 痞客邦 留言(0) 人氣()