Zuhayr
Zuhayr

Reputation: 352

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.

Upvotes: 6

Views: 6007

Answers (4)

Meenu Meena
Meenu Meena

Reputation: 111

In Fragment make like this..

public class Myfragment extends Fragment {

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

    private Callback callback;

    @Override
    public void onAttach(Activity ac) {
        super.onAttach(ac);
        callback = (Callback) ac;
    }

    @Override
    public void onDetach() {
        callback = null;
        super.onDetach();
    }

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

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.
    }
}

Upvotes: 4

Emre Aktürk
Emre Aktürk

Reputation: 3336

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
    }
})

Upvotes: 7

A. Badakhshan
A. Badakhshan

Reputation: 1043

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.

Upvotes: 2

faranjit
faranjit

Reputation: 1627

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.

Upvotes: 3

Related Questions