首页 > 解决方案 > 使用背景将顶部和底部边框应用于 TextView 不起作用,但前景可以

问题描述

我一直在尝试为 TextView 设置顶部和底部边框,它位于位于 CardView 中的 ConstraintLayout 内:

<androidx.cardview.widget.CardView
    android:id="@+id/ham_frame"
    android:layout_width="244dp"
    android:layout_height="100dp"
    android:layout_marginTop="24dp"
    android:layout_marginEnd="24dp"
    app:cardBackgroundColor="?attr/background"
    app:cardCornerRadius="4dp"
    app:cardElevation="3dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/ham_frame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/textView6"
            android:layout_width="wrap_content"
            android:layout_height="32dp"
            android:background="@drawable/border_top_bottom"
            android:text="TextView"
            android:textAlignment="center"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>

图层列表:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="-2dp" android:left="-2dp" android:right="-2dp">
        <shape android:shape="rectangle">
            <stroke android:width="1dp" android:color="?attr/colorSeperator" />
            <solid android:color="#00000000" />
        </shape>
    </item>
    <item android:bottom="-2dp" android:left="-2dp" android:right="-2dp">
        <shape android:shape="rectangle">
            <stroke android:width="1dp" android:color="?attr/colorSeperator" />
            <solid android:color="#00000000" />
        </shape>
    </item>
</layer-list>

现在,我已经完成了关于如何做到这一点的问题,并遵循了图层列表可绘制的多种变体以设置为 TextView 的背景,但这对我来说根本不起作用(两者都没有呈现边框设备和编辑器)。

取而代之的是,将可绘制对象设置为前景只是工作,但问题是它似乎在 API 23 下不受支持(这是不可接受的)。

这里有多个答案: 是否有一种简单的方法可以在 Android 视图的顶部和底部添加边框? 似乎指示将可绘制对象设置为背景,并且似乎没有人面临同样的问题 - 我可能做错了什么?

编辑:?attr/colorSeperator正确设置为#764AFF1A 双重检查,编辑器 (API 26-29) 和我的 LG 设备 (G7+ Pie) 都不会呈现边框。

在设备上,将可绘制设置为背景: 将可绘制设置为前景:
可绘制设置为背景时 TextView 的屏幕截图,不可见边框

可绘制设置为前景时 TextView 的屏幕截图,彩色边框可见

请注意顶部和左侧边缘的阴影式外观是容器,而不是 TextView(应该显示轻微的紫色边框)。

标签: androidandroid-layout

解决方案


在与 Zain 的问题评论中的讨论中进行探索时,styles我使用的主题(在 下)已将 设置backgroundTint为活动的背景颜色(以及 TextView 所在的其他组件)。

因此,即使背景被设置为可绘制的边框,它也被着色为其父背景的颜色(默认情况下),因此背景无法区分。

但是请注意,backgroundTint在 TextView 上设置显式(虽然样式中存在),并没有使背景可见,因此backgroundTint默认样式优先于单独设置的样式。
这种行为似乎与风格层次结构
相矛盾如果我误解了,请纠正我

TL;DR:如果您遇到类似问题,请检查styles.xml其他修复(可绘制对象本身)中的 backgroundTint 属性。


推荐阅读