首页 > 解决方案 > 如何在线性布局中放置 4 种颜色

问题描述

你能指导我如何在线性布局中放置 4 种颜色,而不是创建 4 个线性布局视图,因为我意识到有更好的方法,但我不知道如何应用它。

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

结果应该如下图所示

图片

标签: android

解决方案


更好用ConstraintLayout

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <ImageView
            android:id="@+id/imgOne"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="#ff00"
            app:layout_constraintBottom_toTopOf="@+id/imgThree"
            app:layout_constraintEnd_toStartOf="@id/imgTwo"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />


    <ImageView
            android:id="@+id/imgTwo"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="#2196F3"
            app:layout_constraintBottom_toTopOf="@+id/imgFour"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toEndOf="@id/imgOne"
            app:layout_constraintTop_toTopOf="parent" />


    <ImageView
            android:id="@+id/imgThree"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="#FFC107"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@id/imgTwo"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/imgOne" />


    <ImageView
            android:id="@+id/imgFour"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="#FF5722"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toEndOf="@id/imgThree"
            app:layout_constraintTop_toBottomOf="@+id/imgTwo" />


</androidx.constraintlayout.widget.ConstraintLayout>

输出

在此处输入图像描述


推荐阅读