简体   繁体   中英

Setting drawable to floating action button ImageView in android

ImageView icon = new ImageView(this);
icon.setImageDrawable(R.drawable.alarm);

When I want to set drawable icon it gives me error that android graphics drawable can not apply to ImageView ?

The problem is you are passing ID of your resource in

icon.setImageDrawable(R.drawable.alarm);

method but this method takes only Drawable as parameter. You should change your above call to this

icon.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.alarm));

Or you should call this method instead.

icon.setImageResource(R.drawable.alarm);

请改用setImageResource(R.drawable.alarm)方法。

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/addPostBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="58dp"
    android:clickable="true"
    android:focusable="true"
    android:padding="0dp"
    android:scaleType="center"
    app:borderWidth="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="@+id/mainBottomNavBar"
    app:maxImageSize="45dp"
    android:backgroundTint="@color/White"
    app:srcCompat="@drawable/add_icon"
    app:useCompatPadding="true" />

Use the srcCompat keyword.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM