我在使用这段代码时遇到了麻烦。我正在尝试通过 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);
}
Run Code Online (Sandbox Code Playgroud)
这是我的 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"/>
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用
imageView.setBackgroundColor(getResources().getColor(R.id.your_color));
imageView.setBackgroundColor(Color.parse("#your_color"));
Run Code Online (Sandbox Code Playgroud)
在api level 23中你可以使用ContextCompat提供的getColor方法:
imageView.setBackgroundColor(ContextCompat.getColor(context,R.id.your_color));
Run Code Online (Sandbox Code Playgroud)
所有上述方法都可以正常工作。希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
6257 次 |
| 最近记录: |