?selectableItemBackgroundBorderless 不工作

问题描述 投票:0回答:7

我正在尝试实现一个使用 Android 的默认 itemBackground 样式的视图(但具有椭圆形背景,用于操作栏项目等)。不知何故,下面的视图根本没有显示背景。如果我将 android:background 更改为 android:foreground 它只显示矩形而不是椭圆形。有没有人知道如何解决这个问题?

<LinearLayout
    app:visibleGone="@{showProfile}"
    android:layout_width="wrap_content"
    android:layout_height="26dp"
    android:layout_alignParentStart="true"
    android:gravity="center"
    android:paddingStart="16dp"
    android:paddingEnd="16dp">

       <ImageView
            android:background="?selectableItemBackgroundBorderless"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:onClick="@{() -> profileCallback.onClick()}"
            android:src="@drawable/profile_image" />

</LinearLayout>
android layout view
7个回答
40
投票

您的代码是正确的,但棘手的是父布局也需要背景。

尝试将

android:background="@android:color/transparent"
或任何其他背景设置为其父背景。在你的情况下是 LinearLayout.


8
投票

那条线不太对。使用:

android:background="?android:attr/selectableItemBackgroundBorderless"

2
投票

如果你有 API 21 及以上版本,你可以尝试

android:background="?android:attr/selectableItemBackgroundBorderless"
代替。

但是,在某些情况下(例如以某种方式位于 ConstraintLayout 内,无论是否直接),这是一个已知问题:

https://issuetracker.google.com/issues/111819099

解决方法的一个例子是改用 FrameLayout,只是为了点击效果。这里:

        <FrameLayout
            android:id="@+id/button" ...
            android:clickable="true" android:focusable="true"
            android:foreground="?attr/selectableItemBackgroundBorderless">

            <androidx.appcompat.widget.AppCompatImageView
                android:layout_width="match_parent" android:layout_height="match_parent" .../>
        </FrameLayout>

如果你有 API 21+,你至少可以设置 foregroundTint 来改变这个效果的颜色。


2
投票

我有类似的错误,可能对某人有帮助:

如果你的父母是 FrameLayout 并且它有另一个有背景的孩子,他们可以覆盖你的 selectableItemBackgroundBorderless


1
投票

对我来说,当我使视图可点击时,问题就解决了。添加 android:clickable="true" 或以编程方式在视图上添加点击监听器。


0
投票

你应该在 ImageView 中使用 android:focusable 属性

<ImageView
        android:background="?selectableItemBackgroundBorderless"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:focusable="true"
        android:onClick="@{() -> profileCallback.onClick()}"
        android:src="@drawable/profile_image" />

0
投票

使用

 android:foreground="?attr/selectableItemBackgroundBorderless"

  `android:clipChildern="false"  
   android:clipToPadding="false"`

对于所有父布局

© www.soinside.com 2019 - 2024. All rights reserved.