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

44 views Asked by At

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

2

There are 2 answers

0
Vlad Guriev On BEST ANSWER

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

0
Nebrass wahaib On

You can modify your code like this:

  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();
            return true; // Return true to consume the long click event
        });
    
        return binding.getRoot();
    }