无法在ImageView上使用setForeground方法

Sar*_*gis 12 android imageview

我想使用setForeground方法在我的ImageView中心显示一个"播放"图标,以指示用户按下它时视频将播放.

目前我遇到了这个我无法解决的错误:

在此输入图像描述

虽然文档说自API 1以来该方法应该可用:

在此输入图像描述

我正在使用构建工具版本23.0.1针对API 23进行目标和编译.我的目标是最低API 16.

Com*_*are 28

这是一个文档错误.setForeground()存在于FrameLayoutAPI级别1; 它仅适用于ViewAPI级别23.

  • @Saragis:关闭袖口,让"常规图像"成为`ImageView`的背景图像,并将播放图标作为`ImageView`的实际图像 (3认同)

blu*_*are 6

由于该setForeground方法是为FrameLayoutAPI 级别 1 添加的,作为一种解决方法,您可以将视图包装在 a 中,FrameLayout然后将该setForeground方法用于布局,它将起作用,例如:

在您的 xml 中:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/fl_item_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/niImageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:contentDescription="@string/imageView_description"
        android:scaleType="fitCenter"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</FrameLayout>
Run Code Online (Sandbox Code Playgroud)

然后在代码中,使用:

holder.flItemContainer.setForeground(ContextCompat.getDrawable(a, R.drawable.play));
Run Code Online (Sandbox Code Playgroud)