如何检查哪个当前图像资源附加到android xml中的ImageView? [英] How to check which current image resource is attached to ImageView in android xml?

查看:59
本文介绍了如何检查哪个当前图像资源附加到android xml中的ImageView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查xml中将哪个图像资源附加到ImageView,我能够检查哪个图像资源被附加到图像视图,但是我的要求是如何检查ImageView是否具有相同的资源基于我需要执行一些操作,我是否已将其设置为xml代码始终执行其他部分.以下是我的代码,

I want to check which image resource is attached to ImageView in xml, I am able to check that which image resource is attached to image view but my requirement is to how to check that the ImageView has the same resource which I have set into xml or not, based on that I need to perform some actions.Code always executes else part. Following is my code,

  if (regProfile.getDrawable() == getResources().getDrawable( R.drawable.ivpic)) 
    {
      Toast.makeText(_con, "Image is ivPic", Toast.LENGTH_LONG).show(); 
      // new RegisterAsyntaskNew().execute(); 
    } 
  else 
    {
     Toast.makeText(_con, "Image isn't ivPic", Toast.LENGTH_LONG).show(); 
     // new RegisterAsyntask().execute(); 
    }

推荐答案

请尝试以下操作

if (regProfile.getDrawable().getConstantState() == getResources().getDrawable( R.drawable.ivpic).getConstantState()) 
{
  Toast.makeText(_con, "Image is ivPic", Toast.LENGTH_LONG).show(); 
  // new RegisterAsyntaskNew().execute(); 
} 
else 
{
 Toast.makeText(_con, "Image isn't ivPic", Toast.LENGTH_LONG).show(); 
 // new RegisterAsyntask().execute(); 
}

请使用.getConstantState()进行比较

访问

http://developer.android.com/reference/android/graphics/drawable/Drawable.html

http://developer.android.com/reference/android/graphics/drawable/Drawable.ConstantState.html

.getResources().getDrawable(imageResource)

API21中已弃用,因此我更改了Jitesh Upadhyay的答案.

Is deprecated in API21, so I changed Jitesh Upadhyay's answer.

这是代码:

@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
public static boolean checkImageResource(Context ctx, ImageView imageView,
        int imageResource) {
    boolean result = false;

    if (ctx != null && imageView != null && imageView.getDrawable() != null) {
        ConstantState constantState;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            constantState = ctx.getResources()
                    .getDrawable(imageResource, ctx.getTheme())
                    .getConstantState();
        } else {
            constantState = ctx.getResources().getDrawable(imageResource)
                    .getConstantState();
        }

        if (imageView.getDrawable().getConstantState() == constantState) {
            result = true;
        }
    }

    return result;
}

这篇关于如何检查哪个当前图像资源附加到android xml中的ImageView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆