Android橫豎屏切換View設定不同尺寸或等比例縮放的XML解決方案

來源:互聯網
上載者:User

標籤:.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
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent">  
  5.   
  6.     <TextView  
  7.         android:layout_width="200dp"  
  8.         android:layout_height="150dp"  
  9.         android:layout_centerInParent="true"  
  10.         android:background="@android:color/holo_red_light"  
  11.         android:gravity="center"  
  12.         android:text="橫屏" />  
  13.   
  14. </RelativeLayout>  



res/layout-port/activity_main.xml:

[html] view plain copy http://www.woaipu.com/shops/zuzhuan/61406
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent">  
  5.   
  6.     <TextView  
  7.         android:layout_width="133dp"  
  8.         android:layout_height="100dp"  
  9.         android:layout_centerInParent="true"  
  10.         android:background="@android:color/holo_red_light"  
  11.         android:gravity="center"  
  12.         android:text="豎屏" />  
  13.   
  14. </RelativeLayout>  

 

代碼檔案結構:

 http://www.woaipu.com/shops/zuzhuan/61406

代碼在橫豎屏切換時候的運行結果:
橫屏:

http://www.woaipu.com/shops/zuzhuan/61406

Android橫豎屏切換View設定不同尺寸或等比例縮放的XML解決方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.