2015-05-28 24 views
-2

我在我的應用程序中使用setColorFilter來更改Button的背景顏色。setColorFilter在Android 5.0中不工作

這是我的代碼:

// layout_main.xml 
... 
<Button 
    android:id="@+id/btn_search" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:background="@drawable/btn_round" 
    android:text="button"/> 
    ... 

================================== ==================

// btn_round.xml 
<?xml version="1.0" encoding="utf-8"?> 
    <shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle"> 
    <solid android:name="solid" android:color="#000000"/> 
    <corners 
    android:bottomRightRadius="10dp" 
    android:bottomLeftRadius="10dp" 
    android:topLeftRadius="10dp" 
    android:topRightRadius="10dp"/> 
    </shape> 

========================= ===========================

//MainActivity.java 
... 
Button btn_search = (Button)findViewById(R.id.btn_serach); 
btn_search.getBackground().setColorFilter(Color.RED, Mode.MULTIPLY); 

我試過Mode.MULTIPLY和Mode.OVERLAY。而結果是:

enter image description here

我預計將有ColorFilter似乎背後隱藏的按鈕效果。

此代碼在Android 4.4中運行良好。 但是當我更新Android 5.0時,此代碼不起作用。

我該如何解決這個問題?

+0

如果使用白色(#FFF),如繪製的純色,會發生什麼? – FunkTheMonk

+0

哇這是工作!真的謝謝你,FunktheMonk! – vvThat

回答

3

試試這個

Drawable background = getResources().getDrawable(R.drawable.btn_round); 
background.setColorFilter(new PorterDuffColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY)); 
btn_search .setBackground(background); // Use setBackgroundDrawable for API<16 
btn_search .setVisibility(View.VISIBLE); 
相關問題