获取ImageView的颜色
Get color of ImageView
我想获取我之前设置过颜色的 imageView
的颜色 ID。
ImageView im = findViewById(R.id.imageView);
im.setBackgroundColor(R.color.green);
我该怎么做?
int colorId = im.getBackgroundColorResourceId() // how do I do this?
ImageView
class 中没有检索 ImageView
颜色的函数,因为它们不是设计为被赋予颜色而是被设计为被赋予要显示的图像(因此得名 ImageView
)。如果您希望能够检索 ImageView
已设置的颜色,您可以创建具有所需功能的自定义 ImageView
class。
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
public class CustomImageView extends ImageView {
int backgroundColor;
public CustomImageView(Context context) {
super(context);
}
public CustomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void setBackgroundColor(int color) {
super.setBackgroundColor(color);
backgroundColor = color;
}
public int getBackgroundColor() {
return backgroundColor;
}
}
此自定义 class、CustomImageView
将覆盖函数 setBackgroundColor(int color)
并在这样做时将颜色存储到变量并设置背景颜色,以便它可以稍后检索。函数 getBackgroundColor()
可用于检索此变量。
这不是最简单的解决方案,我相信还有很多其他解决方案,但这个对我来说最有意义。
我想获取我之前设置过颜色的 imageView
的颜色 ID。
ImageView im = findViewById(R.id.imageView);
im.setBackgroundColor(R.color.green);
我该怎么做?
int colorId = im.getBackgroundColorResourceId() // how do I do this?
ImageView
class 中没有检索 ImageView
颜色的函数,因为它们不是设计为被赋予颜色而是被设计为被赋予要显示的图像(因此得名 ImageView
)。如果您希望能够检索 ImageView
已设置的颜色,您可以创建具有所需功能的自定义 ImageView
class。
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
public class CustomImageView extends ImageView {
int backgroundColor;
public CustomImageView(Context context) {
super(context);
}
public CustomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void setBackgroundColor(int color) {
super.setBackgroundColor(color);
backgroundColor = color;
}
public int getBackgroundColor() {
return backgroundColor;
}
}
此自定义 class、CustomImageView
将覆盖函数 setBackgroundColor(int color)
并在这样做时将颜色存储到变量并设置背景颜色,以便它可以稍后检索。函数 getBackgroundColor()
可用于检索此变量。
这不是最简单的解决方案,我相信还有很多其他解决方案,但这个对我来说最有意义。