[英]Android: How to compare resource of an image with R.drawable.imagename?
I am working on a sample application in which I need to get the resource of an image view in a onClick listener and compare that with the image source that I know exists.我正在开发一个示例应用程序,我需要在 onClick 侦听器中获取图像视图的资源,并将其与我知道存在的图像源进行比较。 If the resources are the same, I want to launch another intent.
如果资源相同,我想启动另一个意图。 The problem I am facing right now is to access that ImageView (and hence its resource Id integer) to compare to the drawable resource.
我现在面临的问题是访问 ImageView (以及它的资源 ID 整数)以与可绘制资源进行比较。
@Override
// should int be final ??
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// This is not working and I need to find a way to solve this >>
if (((ImageView)v).getResources().getInteger(0) == R.drawable.imageToCompare)
{
// do nothing
}
else
{
// do something
}
You can't get a drawable id from an ImageView
.您无法从
ImageView
获得可绘制 ID。 But if you set it from code, you can also store it somewhere, for example in the tag field.但是如果你从代码中设置它,你也可以将它存储在某个地方,例如在标签字段中。 Take a look at the similar question: Who I compare an background Image resource TextView with a R.drawable.bg_image for switch .
看看类似的问题:我将背景图像资源 TextView 与 R.drawable.bg_image 进行比较。
if(((ImageView)v).getDrawable().getConstantState() == MainActivity.this
.getResources().getDrawable(R.drawable.unlock)
.getConstantState()))
{
// Do Something
}
The proper way is to user setTag()
and getTag
.正确的方法是使用
setTag()
和getTag
。 I guess you are making your own adapter.我猜你正在制作自己的适配器。
In the method public View getView(int position, View convertView, ViewGroup parent)
, you set tag to Imageview
when you add other properties to it.在
public View getView(int position, View convertView, ViewGroup parent)
方法中,当您向其添加其他属性时,您将标签设置为Imageview
。
ImageView temp = (ImageView) v.findViewById(resId);
temp.setImageResource(icon);
temp.setTag(icon); //drawable unique ID will be my identifier here
Then in the onClick
you simply compare View v
with your drawable
id.然后在
onClick
中,您只需将View v
与您的drawable
id 进行比较。 For example, I wanted to change image on click and I coded it this way.例如,我想在点击时更改图像,并以这种方式编码。 Take notice how I also change tag when I set a new drawable
请注意我在设置新的可绘制对象时如何更改标签
img.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if ((Integer)v.getTag() == R.drawable.current_img) {
v.setBackgroundResource(R.drawable.new_img);
v.setTag(R.drawable.new_img);
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.