如何使用Java代码在Android中更改ImageView的背景颜色

4

我遇到了代码问题。我想通过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"/>

那么问题出在哪里呢?你有收到任何错误吗?你看到了什么奇怪的东西吗?请详细说明你的问题。 - Viral Patel
2个回答

5

您可以选择使用

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));

所有上述方法都可以正常工作。希望这能有所帮助!

它还是不起作用...我想知道为什么 imgView1.setBackgroundColor(Color.RED)不起作用....请帮帮我。 - Seung Joo Noh
如果您观察它,它接受对象而不是资源ID。如果您直接使用资源ID,Android将无法将其识别为颜色。您应该使用上述推荐的方法。当您直接指定颜色ID时,Android Studio也会显示警告。 - Krishna Satwaji Khandagale

3

请尝试使用以下方法

backgroundImg.setBackgroundColor(Color.parseColor("#ff0000"));

或者
backgroundImg.setBackgroundColor(Color.rgb(255, 0, 0));

此外,在设置颜色后,您可能需要使视图无效:
```java view.invalidate(); ```
backgroundImg.invalidate();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接