亲宝软件园·资讯

展开

Android中比较两个图片是否一致的问题

Jason~JiaoJiaoOne 人气:0

  在Fragment界面中,设置两个图片一致如下:

 默认设置图片为:

binding.ivArrow.setImageResource(R.drawable.icon_down);

 先获取默认图片,再和其它两张图片做对比,然后处理业务逻辑:

Drawable.ConstantState ivArrow = binding.ivArrow.getDrawable().getCurrent().getConstantState();
        Drawable.ConstantState icon_up = getDrawable(R.drawable.icon_up).getConstantState();
        Drawable.ConstantState icon_down = getDrawable(R.drawable.icon_down).getConstantState();
        Log.e("--->ivArrow$", "$" + ivArrow);
        Log.e("--->icon_up$", "$" + icon_up);
        Log.e("--->icon_down", "$" + icon_down);
        if (ivArrow.equals(icon_up)) {
          binding.ivArrow.setImageResource(R.drawable.icon_down);
        } else if (ivArrow.equals(icon_down)) {
          binding.ivArrow.setImageResource(R.drawable.icon_up);
        }

打印结果如下:

显然通过日志发现,每个图片的资源都不一致,这是为什么,通过点击getDrawable查看源码发现

这个不是我们想要的,我们要的是id,怎么解决呢,因为是在Fragment中,所以要加上 getActivity()

设置完后,看下效果

完整代码如下:

Drawable.ConstantState ivArrow = binding.ivArrow.getDrawable().getCurrent().getConstantState();
        Drawable.ConstantState icon_up = getActivity().getDrawable(R.drawable.icon_up).getConstantState();
        Drawable.ConstantState icon_down = getActivity().getDrawable(R.drawable.icon_down).getConstantState();
        Log.e("--->ivArrow$", "$" + ivArrow);
        Log.e("--->icon_up$", "$" + icon_up);
        Log.e("--->icon_down", "$" + icon_down);
        if (ivArrow.equals(icon_up)) {
          binding.ivArrow.setImageResource(R.drawable.icon_down);
        } else if (ivArrow.equals(icon_down)) {
          binding.ivArrow.setImageResource(R.drawable.icon_up);
        }

加载全部内容

相关教程
猜你喜欢
用户评论