首页 > 解决方案 > 如何给我的图像添加点击效果?

问题描述

我有一个图像,我想创建一个按钮点击效果 - 当按钮被触摸时,它应该会立即改变颜色。

我查看了下面的链接,但它对我不起作用:

如何在 Android 上提供像按钮一样的 imageview 点击效果?

setColorFilter 不工作

也许是我的安卓版本,即 Lollipop。尽管我在上面的链接中尝试了建议,但它不起作用。我的图像不会改变并且保持相同的颜色。

这是我的代码:

 //into the toolbar, inflate the back button and Populisto title,
    //which we find in toolbar_custom_view_layout.xml
    View logo = getLayoutInflater().inflate(R.layout.toolbar_custom_view_layout, null);
    toolbar.addView(logo);

    ImageView backButton = (ImageView) logo.findViewById(R.id.back_arrow_id);
    backButton.setBackgroundColor(Color.rgb(100, 100, 50));

    //set the ontouch listener
    backButton.setOnTouchListener(new View.OnTouchListener() {

      @Override
      public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {
          case MotionEvent.ACTION_DOWN: {
            ImageView view = (ImageView) v;
            view.getDrawable().setColorFilter(Color.BLACK, PorterDuff.Mode.MULTIPLY);
            view.invalidate();
            break;
          }
          case MotionEvent.ACTION_UP:
          case MotionEvent.ACTION_CANCEL: {
            ImageView view = (ImageView) v;
            //clear the overlay
            view.getDrawable().clearColorFilter();
            view.invalidate();
            break;
          }
        }

        return false;
      }

    });

标签: androidimage

解决方案


return false;

它似乎不接受您所写声明的更改。请将其更改为以下内容:

return true;

还有什么问题,欢迎提问:)


推荐阅读