DEV Community

bongbonglemon
bongbonglemon

Posted on

How do I define a method with input parameters in an interface?

I was following a tutorial at this link: https://info448.github.io/fragment-viewpager.html that covers making an app that allows the user to slide across fragments.

I managed to complete the app but only with partial understanding. I don't understand the part where the fragment communicates with the containing Activity via an interface defined in the Fragment class.

From the Fragment class:

    interface OnSearchListener {
        // allow the Fragment to pass the entered search term to the Activity
        void onSearchSubmitted(String searchTerm);
    }

    OnSearchListener mListener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_search, container, false);

        mButton = (Button) rootView.findViewById(R.id.btn_search);
        editText = (EditText) rootView.findViewById(R.id.txt_search);

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.onSearchSubmitted(editText.getText().toString());
            }
        });

        return rootView;
    }

https://thepracticaldev.s3.amazonaws.com/i/ixjgidx1jw7v4iubj0n7.png

From the Activity class:

    @Override
    public void onSearchSubmitted(String searchTerm) {
        mSearchTerm = searchTerm;
        numberOfPages = 2;
        // simply creating a different Fragment will not
        // cause the Adapter to change—you need to let the
        // Adapter know that the model it is adapting into has changed!
        adapter.notifyDataSetChanged();
        viewPager.setCurrentItem(1);
    }

https://thepracticaldev.s3.amazonaws.com/i/h686v5sxwgfxea0gdk76.png

How making an instance variable of the interface in the Fragment class, and then calling its method onSearchSubmitted(editText.getText().toString()) in the onClick method, allow the input parameter to be transferred to the containing Activity.

To explore this, I went to look at other @Override methods that had input parameters which seemed to have been dealt with in the origin interface such as
onCreate(Bundle savedInstanceState). However, I could not find where in the framework savedInstanceState had already been instantiated and fed into the interface.

I also could not find YouTube tutorial or article that gave examples of implementing interface in this manner i.e having a method with input parameters that a developer is not required to change.

Please help and thank you for reading my post.

Top comments (0)