![](/img/trans.png)
[英]Android : Is it possible to change background color of ImageView with setColorFilter?
[英]How to change background color of ImageView in Android using java code
我在使用此代碼時遇到麻煩。 我正在嘗試通過Java代碼更改ImageView的背景顏色。 當我嘗試此操作時,imageView中根本沒有任何更改。 我試圖通過xml更改背景顏色,但效果很好。 但是通過java,它不起作用。 這是為什么? 我的代碼有什么問題嗎?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonClick();
}
public void buttonClick(){
ImageView imgView1 = (ImageView) findViewById(R.id.image0);// i have an imageView in my resources in XMl.
imgView1.setBackgroundColor(Color.RED);
}
這是我的xml部分
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<GridLayout
android:layout_width="match_parent"
android:layout_height="400dp"
android:columnCount="3"
android:rowCount="3"
android:id="@+id/gridLayout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true">
<ImageView
android:layout_columnWeight="1"
android:layout_rowWeight="1"
android:id="@+id/image0"
android:layout_row="0"
android:layout_column="0"/>
請嘗試
backgroundImg.setBackgroundColor(Color.parseColor("#ff0000"));
要么
backgroundImg.setBackgroundColor(Color.rgb(255, 0, 0));
此外,設置顏色后,您可能需要使視圖無效:
backgroundImg.invalidate();
您可以使用
imageView.setBackgroundColor(getResources().getColor(R.id.your_color));
imageView.setBackgroundColor(Color.parse("#your_color"));
在api級別23中,您可以使用ContextCompat提供的getColor方法:
imageView.setBackgroundColor(ContextCompat.getColor(context,R.id.your_color));
上述所有方法都可以正常工作。 希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.