如何使用java代码在Android中更改ImageView的背景色
我在使用此代码时遇到问题。我试图通过java代码更改ImageView的背景色。当我尝试此操作时,imageView中没有任何更改。我试图通过xml改变背景颜色,效果很好。但是通过java,它不起作用。为什么呢?我的代码有什么问题吗如何使用java代码在Android中更改ImageView的背景色,java,android,Java,Android,我在使用此代码时遇到问题。我试图通过java代码更改ImageView的背景色。当我尝试此操作时,imageView中没有任何更改。我试图通过xml改变背景颜色,效果很好。但是通过java,它不起作用。为什么呢?我的代码有什么问题吗 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.a
@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.invalidate();
请试一下
backgroundImg.setBackgroundColor(Color.parseColor("#ff0000"));
或
此外,您可能需要在设置颜色后使视图无效:
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));
上述所有方法都可以很好地工作。希望这有帮助 您可以使用
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);如果您观察到它接受对象而不是资源id,请帮助我。如果您直接使用资源id,android将不会将其标识为颜色。您应该使用以上推荐的方法。Android studio在您直接指定颜色id时也会显示警告。它仍然不起作用。。。我想知道为什么imgView1.setBackgroundColor(Color.RED);如果您观察到它接受对象而不是资源id,请帮助我。如果您直接使用资源id,android将不会将其标识为颜色。您应该使用以上推荐的方法。当您直接指定颜色id时,Android studio也会显示警告。