Android 减少无用布局

讲一下android studio Inspect Code中的Android > Lint > Performance >UseLess parent layout。

场景

在布局对齐的时候,总是会写一个RelativeLayout去包裹好几个child View,再通过设置centerInParent去控制居中。这时候AS往往会给出warning,parent is possibly useless。

原因分析

添加了一个不必要的额外的视图(增加你的布局深度)。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/detailLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
        <Button
            android:id="@+id/downloadFormsButton"
            android:enabled="false"
            android:layout_alignParentLeft="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="@string/download_forms_button" />
        <TextView
            android:id="@+id/formErrorMsg"
            android:layout_alignParentRight="true"
            android:layout_alignParentBottom="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:textSize="16dp" >
        </TextView>
    </RelativeLayout>
</LinearLayout>

ps:如果加一个background,warning就没有了。

解决方法

  1. 如果布局简单,不影响,直接删除父布局

  2. 使用space和Linenarlayout,并设置layout_weight来控制居中

  3. 充分使用TextView的drawable属性(drawableTop)

  4. 如果是root layout,那么可以在inflate的时候,注意参数的传值

     public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
    

当root不为null,attachToRoot为true时,表示将resource指定的布局添加到root中,添加的过程中resource所指定的的布局的根节点的各个属性都是有效的

如果我想让linearlayout的根节点有效,又不想让其处于某一个容器中,那我就可以设置root不为null,而attachToRoot为false

总结

以上所有内容对过度绘制完全没有作用

备注

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。