Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use setForeground method on ImageView [duplicate]

I want to use the setForeground method to show a "play" icon in the center of my ImageView to indicate the user that a video will play if they press it.

Currently I'm having this error which I cannot solve:

enter image description here

Although the documentation says the method should be available since API 1:

enter image description here

I'm targeting and compiling against API 23 with build tools version 23.0.1. I'm targeting min API 16.

like image 909
Saragis Avatar asked Oct 18 '15 18:10

Saragis


2 Answers

That is a documentation bug. setForeground() existed on FrameLayout from API Level 1; it is only on View as of API Level 23.

like image 130
CommonsWare Avatar answered Nov 16 '22 05:11

CommonsWare


Since the setForeground method was added for the FrameLayout in API Level 1, as a workaround you can wrap your view inside a FrameLayout then use the setForeground method to the layout, it will work, eg:

in your 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>

Then in code, use:

holder.flItemContainer.setForeground(ContextCompat.getDrawable(a, R.drawable.play));
like image 40
blueware Avatar answered Nov 16 '22 06:11

blueware