【问题标题】:Highlight a Button : Setcolor filer not working突出显示按钮:设置滤色器不起作用
【发布时间】:2013-04-20 22:39:02
【问题描述】:

我想在按下并释放时突出显示一个按钮而不使用任何图像,所以我使用 SO 帖子中的以下代码,但它对我不起作用:

public class MainActivity extends Activity {

    ImageButton myButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myButton = (ImageButton) findViewById(R.id.button);
    myButton.setOnTouchListener(new ButtonHighlighterOnTouchListener(myButton));
    }

    public class ButtonHighlighterOnTouchListener implements OnTouchListener {

    final ImageButton imageButton;

    public ButtonHighlighterOnTouchListener(final ImageButton imageButton) {
        super();
        this.imageButton = imageButton;
    }

    @Override
    public boolean onTouch(final View view, final MotionEvent motionEvent) {
        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
        //grey color filter, you can change the color as you like
        imageButton.setColorFilter(Color.parseColor("#5F2444"));
        System.out.println("called down");
        } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
        imageButton.setColorFilter(Color.parseColor("#245F30"));
        System.out.println("called up");
        }
        return false;
    }

    }

这里有什么问题?

原帖在这里:How to make Button highlight?

【问题讨论】:

  • 你需要点击/悬停效果吗?
  • @Abhi 你好哥们我需要点击效果哥们
  • 你为什么不简单地使用选择器?
  • 我需要以编程方式进行
  • @Abhi 我自己解决了我需要你的更多帮助

标签: android button highlight


【解决方案1】:

好的,我自己解决了,希望对其他人也有帮助

public static void buttonEffect(View button) {
    button.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN: {
            v.getBackground().setColorFilter(0xe0f47521, PorterDuff.Mode.SRC_ATOP);
            v.invalidate();
            break;
        }
        case MotionEvent.ACTION_UP: {
            v.getBackground().clearColorFilter();
            v.invalidate();
            break;
        }
        }
        return false;
        }
    });
    }

你也可以改变颜色,愉快的编码:)

【讨论】:

    【解决方案2】:

    我建议你在开关中添加这个事件,否则当用户点击按钮并按住直到他离开按钮时,按钮仍然被选中。

    case MotionEvent.ACTION_CANCEL:
    {
        v.getBackground().clearColorFilter();
        v.invalidate();
        break;
    }
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-17
      • 1970-01-01
      • 2011-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多