appLogic appLogic - 4 months ago 26
Android Question

Android floating button change drawable image

I have an floating button in my app. The xml layout of my floating button is the below

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
>

<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsing_toolbar"
>


<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
/>

</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>


<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">

</android.support.v4.widget.NestedScrollView>


<android.support.design.widget.FloatingActionButton
android:id="@+id/chrono_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/fab_margin"
android:clickable="true"
android:src="@drawable/ic_add_black_48dp"
app:layout_anchor="@+id/appbar"
app:layout_anchorGravity="bottom|right|end" />

</android.support.design.widget.CoordinatorLayout>


What i want is to change the floating button image src programatically when somethings happens. What i tried so far is

chrono_button.setBackground(getDrawable(R.drawable.ic_done_black_48dp));


But i always get this error
I/FloatingActionButton: Setting a custom background is not supported.

What is wrong in my code or is there any ather approach to change the drawable image of a floating button programatically?

Answer

You don't need change the background, set the image.

floatingActionButton.setImageDrawable(getResources().getDrawable(R.drawable.ic_full_sad));
Comments