Home » Java » Listening for activity button clicks from inside a fragment

Listening for activity button clicks from inside a fragment

Posted by: admin December 28, 2021 Leave a comment


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.


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


In Fragment make like this..

public class Myfragment extends Fragment {

    public interface Callback {
        public void onButtonClicked(View radiobtn);

    private Callback callback;

    public void onAttach(Activity ac) {
        callback = (Callback) ac;

    public void onDetach() {
        callback = null;

    radiobtn.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            if (callback != null) {

In Activity do like this…

public class Myfragment extends Activity implements MyFragment.Callback{

    public void onButtonClicked(View btn) {
        // The radiobutton in MyFragment has been clicked
        myButton.setEnabled(true); // or something like this.


Define an interface called like ClickListenerOnActivity contains a method named onClickInActivity(View v) and implement that in fragment. When click the button in activity call this method of the interface.

You can view this example to see how to implement an interface.


Despite Emre Akturk’s answer isn’t wrong, but it is not the best practice, hence you may attach your Fragment to another Activity and after that, that Activity may not have that View. So, the best way is using an interface. Make your Fragment implements your desired interface and then in onClickListener of your Button, call the interface of that Fragment.