安卓進階:Percent Support Library使用


 

 

  安卓手機有很多種機型、不同的屏幕、不同的分辨率,所以對安卓軟件屏幕適配這一塊的問題一直都不怎么友好。布局方面如果是線性布局LInearLayout的話還好一點,可以使用layout_weight的權重比可以實現控件按屏幕比例來排放。

  但是對於相對布局或者說幀布局這些沒有layout_weight這個屬性的布局來說就比較啰嗦了,如果要實現屏幕比例布局還得在外面再嵌套一個LinearLayout,本來使用相對布局的初衷就是減少布局的嵌套使用的,這樣反復嵌套LinearLayout反而得不償失。

 

  為了解決這個問題谷歌推出了一個百分比布局兼容的函數庫:Android Percent Support Library.現在支持RelativeLayout和FrameLayout的百分比布局,不過聽說有人開源了對LinearLayout的百分比支持,我沒試過。

 

使用:

  Percent函數庫屬於Support Library,在使用它之前得先在app目錄下的buile.gradle文件中的dependencies{}中加入依賴

 

compile "com.android.support:percent:26.+"

 

   注意對應自己的SDK版本,我這里是26版本以上的

 

重新rebuild一下項目就可以使用Percent函數庫中的類了

 

現在我使用這個函數庫中的其中一個類寫一個布局文件

<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#000000"
        app:layout_heightPercent="20%"
        app:layout_widthPercent="70%" />

    <TextView
        android:id="@+id/tv2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_below="@id/tv1"
        android:background="#cfc61d"
        app:layout_heightPercent="70%"
        app:layout_widthPercent="20%" />


</android.support.percent.PercentRelativeLayout>

 可以看到我給定的兩個控件的寬和高都是0,控件大小完全是由百分比(紅色字體)決定的。而且可以看到在引用百分比這個方法時,在他們前面都加了app:作為前綴引用,因為新增加的屬性並不是位於Android命名的空間之內的。

特別提醒:注意看我使用的布局(紅色背景內容)是PercentRelativeLayout而不是RelativeLayout

 

效果:

 

 

 

 

Percent函數庫包含以下三個類:

  • PercentFrameLayout
  • PercentRelativeLayout
  • PercentLayoutHelper

 

 PercentRelativeLayout和PercentFrameLayout這兩個類分別是對RelativeLayout和FrameLayout兩個類的繼承。因此我們還是可以使用兩個父類的屬性和功能,同時PercentRelativeLayouyt和PercentFrameLayout兩個類擴展的百分比特性也可以使用,他們在xml文件中增加的配置屬性如下:

  • layout_widthPercent:用百分比表示寬度
  • layout_heightPercnet:用百分比表示高度
  • layout_marginPercent:用百分比表示View之間的間隔
  • layout_marginLeftPercent:用百分比表示左邊的間隔
  • layout_marginTopPercent:用百分比表示頂部的間隔
  • layout_marginRightPercent:用百分比表示右邊的間隔
  • layout_marginBottomPercent:用百分比表示底部的間隔
  • layout_marginStartPercent:用百分比表示距離第一個View的距離
  • layout_marginEndPercent:用百分比表示距離最后一個View的距離
  • layout_aspectRatio:用百分比表示View的寬高比

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM