简体   繁体   English

Android 浮动按钮更改可绘制图像

[英]Android floating button change drawable image

I have an floating button in my app.我的应用程序中有一个浮动按钮。 The xml layout of my floating button is the below我的浮动按钮的 xml 布局如下

<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.我想要的是在发生某些事情时以编程方式更改浮动按钮图像 src。 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.但我总是收到此错误 I/FloatingActionButton: 不支持设置自定义背景。

What is wrong in my code or is there any ather approach to change the drawable image of a floating button programatically?我的代码有什么问题,或者是否有任何其他方法可以以编程方式更改浮动按钮的可绘制图像?

One details that might be good clarifying is the setImageDrawable method is available for the FloatingActionButton class but not for View .一个可能需要澄清的细节是setImageDrawable方法可用于FloatingActionButton类,但不可用于View So if you are having issues finding this method just cast the fab like:因此,如果您在查找此方法时遇到问题,只需将 fab 转换为:

((FloatingActionButton)mItemPlaying.getRootView().findViewById(R.id.fab)).setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_play_arrow_white_24dp));

您不需要更改背景,设置图像。

floatingActionButton.setImageDrawable(getResources().getDrawable(R.drawable.ic_full_sad));
fab.setImageResource(R.drawable.yourimagename);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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