我在我的应用程序中使用setColorFilter来更改Button的背景颜色。
这是我的代码:
// 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。结果是:
我预计ColorFilter的效果似乎隐藏在Button背后。
此代码在Android 4.4中运行良好。 但是当我更新Android 5.0时,此代码无效。
我该如何解决这个问题?
答案 0 :(得分:4)
试试这个
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);