標籤:.com class oid jsb port out 重寫 測量 width
在一些應用中,涉及到橫豎屏切換,View要切換成不同大小比例尺寸。為解決這種開發情境,有多種解決方案,比如可以重寫View,實現橫豎切換在onMesure或者此類View的回調方法裡面重新測量重新繪製View的尺寸大小。還有可以在onConfigurationChanged裡面根據當前的橫豎屏切換情況重寫設定View的長寬比例等等。
現在給出一種比較簡單且較為靈活的處理方法:通過寫兩套xml布局,實現在不同橫豎屏切換狀態下的不同大小比例尺寸。這種方案的關鍵做法是在res裡面放置兩個layout,分別叫做layout-land和layout-port。layout-land橫屏時候將被載入,layout-port豎屏時候載入。只需要寫兩個同名的布局檔案,但是要分別放在res/layout-land和layout-port檔案目錄下。這樣在橫豎屏切換時候Android系統就會自動根據當前橫豎屏情況載入相應的布局。
給出一個例子,本例只有一個activity_main.xml,需要在不同橫豎屏切換時候載入不同相應的布局。那麼就分別寫兩個不同activity_main.xml但是同名的布局檔案。
res/layout-land/activity_main.xml:
[html] view plain copy http://www.woaipu.com/shops/zuzhuan/61406
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
-
- <TextView
- android:layout_width="200dp"
- android:layout_height="150dp"
- android:layout_centerInParent="true"
- android:background="@android:color/holo_red_light"
- android:gravity="center"
- android:text="橫屏" />
-
- </RelativeLayout>
res/layout-port/activity_main.xml:
[html] view plain copy http://www.woaipu.com/shops/zuzhuan/61406
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
-
- <TextView
- android:layout_width="133dp"
- android:layout_height="100dp"
- android:layout_centerInParent="true"
- android:background="@android:color/holo_red_light"
- android:gravity="center"
- android:text="豎屏" />
-
- </RelativeLayout>
代碼檔案結構:
http://www.woaipu.com/shops/zuzhuan/61406
代碼在橫豎屏切換時候的運行結果:
橫屏:
http://www.woaipu.com/shops/zuzhuan/61406
Android橫豎屏切換View設定不同尺寸或等比例縮放的XML解決方案