安卓开发:让四个按钮各占屏幕的四分之一宽度

时间:2019-08-06
本文章向大家介绍安卓开发:让四个按钮各占屏幕的四分之一宽度,主要包括安卓开发:让四个按钮各占屏幕的四分之一宽度使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

这样的需求如果在iOS中,基本的思路是获取当前屏幕的宽度screen_width,然后用一个CGFloat类型的变量temp_width记录一下screen_width / 4.f的计算结果,在用temp_width为按钮的width赋值。不管是frame布局还是autolayout布局方式,基本都这样。

但是安卓中实现这样的效果,用的是“布局模式 + 不给定宽度 + 权重”。感觉很优美~

代码如下:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal">
    <Button
        android:layout_width="0dip"
        android:layout_weight="1"
        android:layout_height="@dimen/dp_40"
        android:text="水果"
        />
    <Button
        android:layout_width="0dip"
        android:layout_weight="1"
        android:layout_height="@dimen/dp_40"
        android:text="蔬菜类"
        />
    <Button
        android:layout_width="0dip"
        android:layout_weight="1"
        android:layout_height="@dimen/dp_40"
        android:text="饮料"
        />
    <Button
        android:layout_width="0dip"
        android:layout_weight="1"
        android:layout_height="@dimen/dp_40"
        android:text="烧烤一下"
        />
</LinearLayout>

效果图如下:

参考:【android开发两个按钮各占屏幕一半摆放的方法

原文地址:https://www.cnblogs.com/cchHers/p/11308759.html