“Press and hold” button on Android needs to change states (custom XML selector) using onTouchListener

后端 未结 5 1410
北恋
北恋 2020-12-09 17:01

I\'ve got a button graphic which needs to have \"press and hold\" functionality, so instead of using onClickListener, I\'m using onTouchListener so that the app can react to

5条回答
  •  臣服心动
    2020-12-09 17:29

    I figured it out! Just use view.setSelected() as follows:

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN){
            yourView.setSelected(true);
            ...
            return true;
        }
        else if(event.getAction() == MotionEvent.ACTION_UP){
            yourView.setSelected(false);
            ...
            return true;
        }
        else 
            return false;
    }
    

    That'll make your selector work even if your view has an onTouch listener :)

提交回复
热议问题