How to handle button clicks using the XML onClick within Fragments How to handle button clicks using the XML onClick within Fragments xml xml

How to handle button clicks using the XML onClick within Fragments


I prefer using the following solution for handling onClick events. This works for Activity and Fragments as well.

public class StartFragment extends Fragment implements OnClickListener{    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,            Bundle savedInstanceState) {        View v = inflater.inflate(R.layout.fragment_start, container, false);        Button b = (Button) v.findViewById(R.id.StartButton);        b.setOnClickListener(this);        return v;    }    @Override    public void onClick(View v) {        switch (v.getId()) {        case R.id.StartButton:            ...            break;        }    }}


You could just do this:

Activity:

Fragment someFragment;    //...onCreate etc instantiating your fragmentspublic void myClickMethod(View v) {    someFragment.myClickMethod(v);}

Fragment:

public void myClickMethod(View v) {    switch(v.getId()) {        // Just like you were doing    }}    

In response to @Ameen who wanted less coupling so Fragments are reuseable

Interface:

public interface XmlClickable {    void myClickMethod(View v);}

Activity:

XmlClickable someFragment;    //...onCreate, etc. instantiating your fragments casting to your interface.
public void myClickMethod(View v) {    someFragment.myClickMethod(v);}

Fragment:

public class SomeFragment implements XmlClickable {//...onCreateView, etc.@Overridepublic void myClickMethod(View v) {    switch(v.getId()){        // Just like you were doing    }}    


The problem I think is that the view is still the activity, not the fragment. The fragments doesn't have any independent view of its own and is attached to the parent activities view. Thats why the event ends up in the Activity, not the fragment. Its unfortunate, but I think you will need some code to make this work.

What I've been doing during conversions is simply adding a click listener that calls the old event handler.

for instance:

final Button loginButton = (Button) view.findViewById(R.id.loginButton);loginButton.setOnClickListener(new OnClickListener() {    @Override    public void onClick(final View v) {        onLoginClicked(v);    }});