【问题标题】:Arranging elements with equal spacing in layout在布局中以等间距排列元素
【发布时间】:2017-06-30 06:09:54
【问题描述】:

我目前使用LinearLayoutlayout_weight 得到以下结果。

┌─────────────────────────────────────────────────────────────────────────────┐ 
│        ┌───┐              ┌───┐              ┌───┐             ┌───┐        │ 
│        │   │              │   │              │   │             │   │        │ 
│        └───┘              └───┘              └───┘             └───┘        │ 
└─────────────────────────────────────────────────────────────────────────────┘ 
                                                                  LinearLayout  

使用它,我得到在父布局中等距的元素。我想要的结果是,第一个和最后一个元素应该位于布局每一侧的末尾,并且与内部元素等距。为了实现这一目标应该做些什么?表示如下。

┌─────────────────────────────────────────────────────────────────────────────┐ 
├───┐                    ┌───┐                   ┌───┐                    ┌───┤ 
│   │                    │   │                   │   │                    │   │ 
├───┘                    └───┘                   └───┘                    └───┤ 
└─────────────────────────────────────────────────────────────────────────────┘ 
                                                                     Layout 

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    您可以将 Space 视图与 layout_weight 结合使用,以便在元素之间创建相等的间距。

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <View
        android:background="@color/black"
        android:layout_weight="1"
        android:layout_width="45dp"
        android:layout_height="wrap_content"/>
    
    <Space
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    
    <View
        android:background="@color/black"
        android:layout_weight="1"
        android:layout_width="45dp"
        android:layout_height="wrap_content"/>
    
    <Space
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    
    <View
        android:background="@color/black"
        android:layout_weight="1"
        android:layout_width="45dp"
        android:layout_height="wrap_content"/>
    </LinearLayout>
    

    【讨论】:

    • 我正在尝试你的方法,但是当我尝试在上面的代码中添加 imageview 而不是 view 时,图像会拉伸。知道如何克服这个问题吗?
    • 如何在 ImageView 中设置图像?你应该使用android:src="@drawable/your_image" 而不是android:background="@drawable/your_image"
    • 它需要一些调整,但按预期工作。谢谢。
    猜你喜欢
    • 2010-10-08
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    相关资源
    最近更新 更多