簡體   English   中英

是否可以在每次單擊時更改浮動操作按鈕的顏色?

[英]Is it possible to change the color of a floating action button every time it is clicked?

我有一個默認顏色為綠色的 FAB,每次單擊它時都可以更改顏色嗎? 例如,從綠色到紅色。

如果可能的話,我想我需要在 color/custom_color.xml 中添加自定義顏色,但是屬性是什么?

嘗試在 xml 中將app:backgroundTint添加到您的FloatingActionButton

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email"
    app:backgroundTint="@color/red"/>

並在您的活動中通過添加點擊偵聽器來更改按鈕顏色:

fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        fab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(MainActivity.this, R.color.blue)));
    }
});

您可以使用setBackgroundTintList()來更新 fab 按鈕的顏色。

 fab.setBackgroundTintList(ColorStateList.valueOf(Color
                    .parseColor("#33691E")));

然后,您只需設置一個 OnclickListener 並在值數組中選擇一個隨機顏色。

// Create list of random colors
ArrayList<String> colors = new ArrayList<>();
colors.add("#33691E");
colors.add("#00AE1E");
colors.add("#45F41E");
//Srt onclicklistener
fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Pick random color
                Random r = new Random();
                int randomIdx = r.nextInt(colors.size());
                // Set background
                fab.setBackgroundTintList(ColorStateList.valueOf(Color
                    .parseColor(colors.get(randomIdx))));
            }
        });

您可以更改浮動操作按鈕的顏色:

<android.support.design.widget.FloatingActionButton
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:src="@drawable/ic_add"
     app:backgroundTint="@color/red"
     app:borderWidth="0dp"
     app:elevation="2dp"
     app:fabSize="normal" >

因此app:backgroundTint是您可以更改 FAB 背景顏色的屬性。

或者如果您想更改圖標顏色:

android:tint="@color/red"  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM