如何在垂直线性布局中更有效地居中视图?

how is more efficient to center a view in a vertical linear layout?

我有一个垂直线性布局,里面有 2 个视图。

如何让这个视图垂直居中?什么是最具成本效益的

1) 将线性布局替换为相对布局并使用 android:center_toparent= true(因为每次渲染都要传递两个布局,所以开销很大)

2) 放置两个占位符视图,一个作为第一个和最后一个子视图。 eachi 与 height = 0weight = 1 所以左边的 space 平均分布。 我可以将这些虚拟视图设​​为 visibility = invisible 吗?它节省了一些成本?

除非您的 activity 会有很多(例如,成百上千)这些视图,否则 不太可能通过或两个额外的间隔视图将产生任何明显的差异。就个人而言,我什至不会费心去衡量这些策略中哪一个是最快的;我会做我团队的标准或我习惯做的任何事情。

节省三纳秒对您的用户没有任何帮助。编写您可以在六个月内回过头来并立即理解的代码将极大地帮助您或您的队友。

我对 "best" 方法的直觉反应(就长期可维护性而言)是在 LinearLayout 上使用 android:gravity 属性。不需要间隔视图。

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

    <View
        android:layout_width="match_parent"
        android:layout_height="96dp"
        android:background="#caf"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="96dp"
        android:background="#fac"/>

</LinearLayout>