经历过html开发前端开发和JAVA开发的朋友们,对上手android开发还是比较快速的,apk开发可以理解为一个是用于显示,一个是用于程序处理。小编对LinearLayout理解为html中的div和前端小程序开发中的view。在html+CSS开发中我们很容易做到两个元素左右对齐。那么在android开发中如何做到左右对齐呢?

LinearLayout布局实现左右对齐

在android中控件LinearLayout 的android:gravity="center"  属性,要么是居左、居右、居中对齐,要实现双控件的左右两端对齐,要采用 中间增加一个控件的方式实现 ,并设置属性android:layout_weight="1",原因是设置android:layout_weight="1",就把控件均分了。

好比如果想让A,C左右对齐,那么需要添加一个B,设置B的属性android:layout_weight="1"就可以了。

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="48dp"
    android:layout_gravity="center">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:text="显示动画效果" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1" />
    <Switch
        android:id="@id/fancyAnimCB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:background="@drawable/switch_style"
        android:checked="true"
        android:showText="false"
        android:switchMinWidth="49dp"
        android:thumb="@null"
        android:track="@null"
        tools:ignore="TouchTargetSizeCheck"></Switch>
</LinearLayout>