Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listening for activity button clicks from inside a fragment

I've just started learning about fragments and I have an activity which is 1000+ lines of code that I've converted to a fragment.

I'm wondering if there is any easy way to allow my fragment to listen to buttons that reside in the XML of it's parent activity. I tried just adding a regular listener in the fragment's onCreateView with the ID of the buttons but it's (expectedly) giving me a null pointer exception.

I do know of the OnSearchClickListener method of doing this but it would probably take a good many hours of manual refactoring to achieve what I need (at least from what I can tell about its usage, I'd be happy to be wrong), so I was wondering if anyone knows of any other method to get this done in a non-repetitive way.

like image 642
Zuhayr Avatar asked Feb 23 '17 10:02

Zuhayr


1 Answers

You can try to get a reference of view in activity this way:

View view = getActivity().findViewById(R.id.view_in_activity);

Then add listener:

view.setOnClickListener(new OnClickListener() {
    void onClick(View v) {
        // Perform some action
    }
})
like image 183
Emre Aktürk Avatar answered Sep 28 '22 06:09

Emre Aktürk