2016-01-02 31 views
1

我对此代码有麻烦。我试图通过Java代码更改我的ImageView的背景颜色。当我尝试这个时,在imageView中根本没有改变。我试图通过XML更改背景颜色,它工作正常。但通过Java,它不起作用。这是为什么?我的代码有什么问题吗?如何使用java代码更改Android中ImageView的背景颜色

@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"/> 
+0

那么是什么问题?你有什么错误吗?你看到奇怪的东西吗?请详细说明你的问题 – AndroidMechanic

回答

2

请尽量使用

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

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

还,您可能需要设置后视图无效颜色:

backgroundImg.invalidate(); 
+0

仍然不起作用:( –

2

您可以使用

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

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

+0

它仍然无法正常工作...我想知道为什么imgView1.setBackgroundColor(Color.RED); 不起作用....请帮助我 –

+0

如果你观察它接受的是对象,而不是资源ID,如果你直接使用资源ID,android不会将它识别为颜色,你应该使用上面推荐的方法,当你直接指定颜色ID时,Android studio也会显示警告。 – Krishna

相关问题