Android中如何使控件保持固定宽高比
目錄
?
1、自定義view
2、adjustViewBounds
3、百分比布局
4、ConstraintLayout
我們在android開發過程中可能會遇到一種情況,一個組件需要保持固定的寬高比,但是組件本身大小卻不定。尤其在android屏幕碎片化的情況下,很多時候我們需要讓一個組件寬度與屏幕寬度一致,這樣就無法確定寬度。那么如何讓控件保持固定寬高比?有幾種方法供大家選擇。
1、自定義view
自定義view,重寫onMeasure或onLayout等相關方法,通過預定的比例計算寬高。
下面是簡單示例:
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {int width = MeasureSpec.getSize(widthMeasureSpec);if (mRatio != 0) {float height = width / mRatio;heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) height, MeasureSpec.EXACTLY);}super.onMeasure(widthMeasureSpec, heightMeasureSpec); }這種方法是很多早期開發者喜歡的方式,但是缺點是需要自己重新自定義一個view。
2、adjustViewBounds
為ImageView設置adjustViewBounds,如下:
android:adjustViewBounds="true"這樣ImageView就會以圖片的寬高比顯示。
但是這個方法的缺點是只能用于ImageView。
3、百分比布局
Android提供了Android-percent-support這個庫,支持百分比布局,包括PercentRelativeLayout和PercentFrameLayout。
使用PercentFrameLayout也可以實現一個組件的固定比例顯示,代碼如下:
需要在res/values下新建一個fraction.xml,代碼如下:
<?xml version="1.0" encoding="utf-8"?> <resources><item name="circle_article_aspectRatio" type="fraction">133%</item> </resources>這樣就實現了寬高4:3的比例。
這個方法的優點是不必自定義view。缺點是組件外層需要包裹一個百分比布局,同時需要一個設置ratio的xml文件。
4、ConstraintLayout
這種方式與百分比布局類似,使用的是ConstraintLayout的DimensionRatio屬性,代碼如下:
<android.support.constraint.ConstraintLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"><ImageViewandroid:layout_width="0dp"android:layout_height="0dp"android:src="@mipmap/bb"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"app:layout_constraintDimensionRatio="4:3"/> </android.support.constraint.ConstraintLayout>這種方法的優點是不用自定義view,相對于百分比布局不需要創建一個設置ratio的xml文件;缺點是需要使用ConstraintLayout。
在上面示例中我們將ImageView的寬高都設置為0。就此我測試了其他的可能性,產生的幾個情況如下:
1、如果組件寬高都設置0dp,組件寬高按比例,且只受父view的約束。如圖
?
2、如果其中一個設置成了wrap_content,比如說寬度,那么寬度就會是 圖片的真實寬度 和 父view的限制寬度 的較小值,而高度會根據寬度和比例計算出來。
這時如果圖片較小,就不會撐滿父View。如圖
3、?
總結
以上是生活随笔為你收集整理的Android中如何使控件保持固定宽高比的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 解读ImageView的wrap_con
- 下一篇: ListView和GridView的缓存