android - 使用约束布局时设置背景

标签 android background android-constraintlayout

我使用约束布局作为父布局,并使用约束添加了多个子布局。水平方向有三个 View ,我必须只为两个 View 应用圆角背景,这是以前通过线性布局实现的。但是在约束布局的帮助下,我无法实现这一点。

我怎样才能做到这一点?

enter image description here

最佳答案

ConstraintLayout 最近引入了 constrainthelper 的概念,可用于对一组 View 执行操作。用于切换多 View 可见性的“组”是此类的子类。

同时更改多个 View 背景的 constrainthelper 还不是稳定版本的一部分,但很快就会是。

在那之前,您可以使用 View 类实现如下例所示的背景,其中 3 个 textview 共享一个公共(public)背景:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="#AAA">

  <View
    android:id="@+id/background"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:background="#FFF"
    app:layout_constraintBottom_toBottomOf="@+id/textView3"
    app:layout_constraintEnd_toEndOf="@+id/textView1"
    app:layout_constraintStart_toStartOf="@+id/textView1"
    app:layout_constraintTop_toTopOf="@+id/textView1" />

  <TextView
    android:id="@+id/textView1"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    android:padding="8dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:text="TextView" />

  <TextView
    android:id="@+id/textView2"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:padding="8dp"
    app:layout_constraintEnd_toEndOf="@+id/textView1"
    app:layout_constraintStart_toStartOf="@+id/textView1"
    app:layout_constraintTop_toBottomOf="@+id/textView1"
    tools:text="TextView" />

  <TextView
    android:id="@+id/textView3"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:padding="8dp"
    app:layout_constraintEnd_toEndOf="@+id/textView1"
    app:layout_constraintStart_toStartOf="@+id/textView1"
    app:layout_constraintTop_toBottomOf="@+id/textView2"
    tools:text="TextView" />
</android.support.constraint.ConstraintLayout>

编辑:A nice blog on what to expect from ConstraintLayout 2.0

关于android - 使用约束布局时设置背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51112085/

相关文章:

java - 如何在不显示黑屏的情况下掩盖来自android服务器的响应所花费的时间?

android - 无法使用 adb screenrecord 从三星 S5 捕获视频

android - Android 浏览器中奇怪的水平滚动

HTML PNG透明图片

java - 图像大小造成计时器问题

android - 使用 ConstraintLayout 在另一个 View 下方制作按钮

Android 谷歌地图 API 11

android - 如何以编程方式创建垂直或水平指南

android - ConstraintLayout beta5 wrap_content 没有正确换行

background - 带背景封面的div