Android :: OnTouchListener && OnClickListener combination issue

前端 未结 3 663
慢半拍i
慢半拍i 2020-12-18 07:34

Problem description:

I have a TextView on a RelativeLayout and I want to color it red when the user touches it, and go on another page whe

3条回答
  •  Happy的楠姐
    2020-12-18 08:15

    Adel, is the problem with the first click, or you don't get any click at all?

    There is this issue if you have multiple clickable layout you don't get any click events for the first. That's because it makes it first selected and then you get the click event, try the below code.

    private class CustomTouchListener implements OnTouchListener {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            TextView tv = (TextView) v.findViewById(R.id.single_line_text);
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                tv.setTextColor(COLOR_WHEN_PRESSED);
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                tv.setTextColor(COLOR_WHEN_RELEASED);
                // Action of click goes here
            } else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
                tv.setTextColor(COLOR_WHEN_RELEASED);
                                // To handle release outside the layout region
            }
            return false;
        }
    }
    

    This is working in my current implementation if you set the touch listener for your layout.

    You also need to set below on your layout

    android:focusable="true"
    android:focusableInTouchMode="true"
    android:clickable="true"
    

    Hope it helps!!!

    EDIT: Additionally, there should be a flag in both DOWN and UP. Set it in DOWN and check if its set in UP. This will avoid a bug where user might tap anywhere in the screen and then hover on your textview and release it.

提交回复
热议问题