layout_weight(权重)是目前最为推荐的Android多屏幕自适应解决方案
- 该属性的作用是决定控件在其父布局中的显示权重,一般用于线性布局中。其值越小,则对应的layout_width或layout_height的优先级就越高,一般横向布局中,决定的是layout_width的优先级;纵向布局中,决定的是layout_height的优先级。
- 传统的layout_weight使用方法是将当前控件的layout_width和layout_height都设置成fill_parent,这样就可以把控件的显示比例完全交给layout_weight;这样使用的话,就出现了layout_weight越小,显示比例越大的情况。不过对于2个控件还好,如果控件过多,且显示比例也不相同的时候,控制起来就比较麻烦了,毕竟反比不是那么好确定的。
解决之道:最为流行的0dp设置法,layout_width=0dp的写法,结合layout_weight,让控件成正比例显示,轻松解决了当前Android开发最为头疼的碎片化问题之一。
<resources>
<style name="MainButtonStyle">
<!-- Customize your theme here. -->
<item name="android:layout_width">0dp</item>//宽度设置为0dp,让权重去匹配
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_weight">1</item>
<item name="android:button">@null</item>
<item name="android:textSize">10sp</item>
<item name="android:gravity">center</item>
</style>
</resources>
接下来Demo布局展示:
android:drawableTop:设置在TextView中图片在文字的上边
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical"
tools:context=".app.MainActivity">
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />//设置权重为1
<RadioGroup
android:id="@+id/rg_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@drawable/home_bottom_parent_bg"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rb_home"
style="@style/MainButtonStyle"
android:drawableTop="@drawable/home_button_selector"
android:text="首页" />
//android:drawableTop:设置在TextView中图片在文字的上边
<RadioButton
android:id="@+id/rb_type"
style="@style/MainButtonStyle"
android:drawableTop="@drawable/type_button_selector"
android:text="分类" />
<RadioButton
android:id="@+id/rb_community"
style="@style/MainButtonStyle"
android:drawableTop="@drawable/community_button_selector"
android:paddingTop="10dp"
android:text="发现" />
<RadioButton
android:id="@+id/rb_cart"
style="@style/MainButtonStyle"
android:drawableTop="@drawable/cart_button_selector"
android:text="购物车" />
<RadioButton
android:id="@+id/rb_user"
style="@style/MainButtonStyle"
android:drawableTop="@drawable/user_button_selector"
android:text="个人中心" />
</RadioGroup>
</LinearLayout>
页面展示: