android Framelayout(幀布局)是很常用的布局,主要用來處理需要多個view疊加顯示的情況。
然而在使用中,我發現Framelayout中的Button控件,會擋住所有其他控件,而不論位置和添加順序如何,這個表現是不正常的,我本機有4.1和5.0兩種模擬器,只有5.0有這個問題,因此懷疑是5.0的bug。
下面用一個例子說明:
想要的效果是這樣的:
我選擇使用Framelayout來實現,下面一個button,上面一個imageview即可,代碼如下:
1 <FrameLayout 2 android:layout_width="match_parent" 3 android:layout_height="wrap_content"> 4 5 6 <Button 7 android:layout_width="match_parent" 8 android:layout_height="wrap_content" 9 android:text="立即投資" /> 10 11 <ImageView 12 android:layout_width="36dp" 13 android:layout_height="36dp" 14 android:layout_gravity="left|center" 15 android:layout_marginLeft="16dp" 16 android:src="@mipmap/ic_invest_button" 17 android:tint="@color/white" /> 18 19 </FrameLayout>
在4.1系統上,工作良好,換到5.0,左邊的小圖標(imageview)死活不顯示,調試了半天才發現是被button的背景遮住了。
imageview是后加入的,按理來說,應該是顯示在button上面,而不應該被擋住,所以覺得這應該是5.0的一個bug。
但是咱們也必須得兼容5.0,不能顯示異常啊,那咱們自己來解決這個問題吧,因為本項目其他地方也用到了Framelayout,沒有出現異常,只有這里異常,對比測試后發現,是button控件的問題,那假如我就用一個容器把button包裹起來,結果會怎么樣呢?直接上代碼:
1 <FrameLayout 2 android:layout_width="match_parent" 3 android:layout_height="wrap_content"> 4 5 <RelativeLayout 6 android:layout_width="match_parent" 7 android:layout_height="wrap_content"> 8 9 <Button 10 android:layout_width="match_parent" 11 android:layout_height="wrap_content" 12 android:text="立即投資" /> 13 14 </RelativeLayout> 15 16 <ImageView 17 android:layout_width="36dp" 18 android:layout_height="36dp" 19 android:layout_gravity="left|center" 20 android:layout_marginLeft="16dp" 21 android:src="@mipmap/ic_invest_button" 22 android:tint="@color/white" /> 23 24 </FrameLayout>
跑起來一看,問題解決了,完美兼容4.0,5.0。只是多了一層嵌套,代碼上看略微不優雅。