Search code examples
javaandroidbuttononlongclicklistener

CircleButton LongClickListener not triggered


I use a CircleButton from the lib MaterialWidget. In my Fragment I try to use a LongClickListener on this component, but it is not working. A ClickListener is working but not the long one.

Lib : https://github.com/keithellis/MaterialWidget/blob/master/library/src/main/java/com/material/widget/CircleButton.java

It is working with a standard button.

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    final View rootView = inflater.inflate(R.layout.fragment_home_home, container, false);

    rootView.findViewById(R.id.cb_startPhotoe).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isLongClickReleased) {
                Intent i = new Intent(getActivity(), NavigationActivity.class);
                i.putExtra("fake", 1);
                startActivity(i);
            }
        }
    });

    rootView.findViewById(R.id.cb_startPhotoe).setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            isLongClickReleased = false;
            displayMenu(rootView);
            return true;
        }
    });
    return rootView;
}

When I see the code of the lib, nothing special appear to me. In debug mode, it the listener is not triggered Even if I comment the OnClickListener, nothing works.


Solution

  • I don't use the particular library but I read the code and found that in the onTouchEvent method, performClick() is called once in MOTION_UP case block. This is what triggers your OnClickListener. Therefore for long click, you need to insert in that method performLongClick() that suits your needs.

    Here's my idea to do long click. It's pretty simple but you need to customize that CircleButton class. So add a class variable say long tsDown;

    private long tsDown;
    
    @Override
    public boolean onTouchEvent(@NonNull MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                 ...
                 tsDown = System.currentTimeMillis();
                 break;
            case MotionEvent.ACTION_UP:
                ...
                if (!mMoveOutside) {
                    long tsUp = System.currentTimeMillis();
                    if (tsUp - tsDown < 1000){
                      // if press duration is below 1s                       
                      performClick();
                    }else{
                      performLongClick();
                    }  
                }
                break;
    
        }
        return true;
    }