?可选项背景无边框不起作用



我正在尝试实现一个使用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:background="@android:color/transparent"或任何其他背景设置为其父级。在你的例子中,它是线性布局。

这句话不太对。用:

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

如果您有 API 21 及更高版本,则可以尝试android:background="?android:attr/selectableItemBackgroundBorderless"

但是,在某些情况下(例如以某种方式在约束布局中,无论是否直接(,这是一个已知问题:

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 来更改此效果的颜色。

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

如果您的父级是FrameLayout,并且它有另一个带背景的子项,他们可以覆盖您的可选项目背景无边框

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

你应该在 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" />

使用android:foreground="?attr/selectableItemBackgroundBorderless"

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

对于所有父布局

最新更新