There is a custom button, from it you need to transfer your parameters to the fragment, for this I use the interface:

public interface ColorButtonClickListener{ public void onClickButton(View view); } 

Now, on click, I call this interface and pass it to the method context:

 ColorButtonClickListener colorButton = (ColorButtonClickListener) getContext(); colorButton.onClickButton(this); 

At the time of the click an exception occurs:

  java.lang.ClassCastException: ua.com.tarde.finish_paint.MainActivity cannot be cast to ua.com.tarde.finish_paint.Views.ColorButton$ColorButtonClickListener at ua.com.tarde.finish_paint.Views.ColorButton.onTouchEvent(ColorButton.java:106) 

The error gives the line where I bring the interface. There is no error when implementing the MainActivity interface. I understand that the fragment does not live separately from the activity, and the problem is somewhere in this. I just do not understand why the implementation of clicks cannot be placed in the fragment, because these buttons are there. That’s the logic of the application is built.

  • Show the class code of the custom button and the fragment markup. While the question is not clear. - post_zeew
  • Thank you, I was answered the question below. - Igor

2 answers 2

The getContext() method must return something that inherits the context. Fragment does not inherit the context and its getContext() method actually calls its getActivity() method. This is how you act out when you request a context.

You need to do this:

  1. In your view, make a field for the link to the interface.
  2. Make a setter for him.
  3. In the fragment implement the interface
  4. After downloading the fragment markup, find your view in the markup and assign it a link to the fragment through the setter from P2
  5. At the right moment, call the interface method from the view through the view variable, which stores the reference to the implementation of the interface, i.e. through the variable from p1

    Not everything at once became clear, but in the end I figured it out. As above and advised:

    1. Made a field for the link to the interface and setter for it.
    2. I found a button in the fragment code and implemented its interface, I passed this through the interface setter. I understand this and there is a link to the fragment. Well, plus in the implemented method of the interface I assigned the necessary actions.

    It all worked. Thank!