美文网首页
Support library 支持使用 % 在 Relativ

Support library 支持使用 % 在 Relativ

作者: 花开堪折枝 | 来源:发表于2016-06-19 23:09 被阅读82次

虽然Android提供了很多中布局方式,但是我们经常用的就三个: LinearLayout, RelativeLayoutFrameLayout

但是在使用RelativeLayoutFrameLayout的时候又会存在这样的问题。当我们需要指定子布局占父布局的百分比时,只有两种方式:

  • 在里面添加LinearLayout使用 layout_weight
  • java代码中重写 onMeasure等。

例如:当我需要指定左边距为父布局的 5%,宽度为父布局的 25%

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="20">
 
        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            />
 
        <View
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_weight="5"
            android:background="#ff0000" />
 
    </LinearLayout>
 
</RelativeLayout>

此时你会发现布局文件变的复杂了好多,也是增加布局的绘制时间。

现在这个已经不是个问题了,在最新发布的Support Library增加在RelativeLayoutFrameLayout的%属性。

Percent Support Library

首先你需要升级你的支持库到 23,因为是在这个版本发布的,然后添加依赖在你的build.gradle文件中:

com.android.support:percent:23.0.0'

使用 android.support.percent.PercentRelativeLayoutandroid.support.percent.PercentFrameLayout分别替代掉 RelativeLayoutFrameLayout。现在有 9个属性可以使用

  • layout_widthPercent : 宽度的百分比 ,例如:app:layout_widthPercent="25%"
  • layout_heightPercent : 高度的百分比
  • layout_marginPercent : 边距的百分比

还其他一些layout_marginLeftPercent, layout_marginRightPercent, layout_marginTopPercent, layout_marginBottomPercent, layout_marginStartPercent, layout_marginEndPercent

现在我们重写一下上面的例子:

<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">
 
    <View
        app:layout_widthPercent="25%"
        android:layout_height="100dp"
        app:layout_marginLeftPercent="5%"
        android:background="#ff0000" />
 
</android.support.percent.PercentRelativeLayout>

两个结果对比:


你会发现结果完全一致,但是代码更简洁,没有添加任何填充的布局,会更好的执行。

来源:https://inthecheesefactory.com/blog/know-percent-support-library/en

Note:这个是一篇以前翻译的文章,博客挂了,恢复到这边。

相关文章

网友评论

      本文标题:Support library 支持使用 % 在 Relativ

      本文链接:https://www.haomeiwen.com/subject/vjobdttx.html