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

时间:2018-09-28 19:09:25

标签: android view android-linearlayout android-layout-weight

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

我如何使该视图垂直居中?最具成本效益的

1)用相对布局替换线性布局,并使用android:center_toparent= true(价格昂贵,因为每次渲染都要经过两次布局)

2)放置两个占位符视图,一个作为第一个孩子,也是最后一个孩子。每个人都有height = 0weight = 1,因此剩余空间会平均分布。 我可以将这些虚拟视图设​​为visibility = invisible吗?节省一些费用吗?

1 个答案:

答案 0 :(得分:0)

除非您的活动将拥有很多(例如成百上千个)这些视图,否则极其不可能一次额外的布局遍历或两个额外的间隔视图会产生明显的变化。就我个人而言,我什至都不会去衡量这些策略中哪一个最快。我只会做我团队中标准的事情或者我曾经做过的事情。

节省3纳秒对您的用户没有任何帮助。编写您可以在六个月后恢复使用并立即理解的代码,将极大地帮助您或您的团队成员。

我对执行此操作的“最佳”方法(长期可维护性)的直觉反应是在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>

enter image description here

相关问题