javaandroiddata-bindingonlongclicklistener

OnLongClickListener and Data Binding - void cannot be converted to boolean (Android, Java)


How can I integrate a longclick listener with data binding? It needs a boolean return. But apparently my method cannot return a value (void)


public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = LayoutTrainBaseItemBinding.inflate(inflater, container, false);


        binding.Button.setOnClickListener(view1 -> myFunction());

        binding.Button.setOnLongClickListener(view1 -> myFunction());

Thank you very much for a tip


Solution

  • View.OnLongClickListener is a SAM-interface whose abstract method returns boolean (unlike View.OnClickListener, where the return type is void).

    If myFunction() returned boolean, the line binding.Button.setOnLongClickListener(view1 -> myFunction()); would work.

    For example, the following will compile in your case:

    binding.Button.setOnLongClickListener(view1 -> {
        myFunction();
        return true;
    });
    

    As for the return value, the docs say:

    true if the callback consumed the long click, false otherwise.

    Please consider it for your logic