Thursday, August 01, 2013

Android Tip: Handling Events in a Fragment

In an activity, handling the Click event of a Button is very easy using the android:onClick attribute and assigning it a method name as the event handler. You then implement the method in your activity. However, if you have a Button in a fragment, using the android:onClick attribute does not cause the event handler to fire in the Fragment class; instead it will fire in the Activity class.

In the spirit of loose coupling in Software Engineering, a better way is to handle the Click event of your button in the fragment directly in the Fragment class.

Assuming in your XML file (activity_detail.xml) for your fragment you have a Button with an id of:

        android:text="OK" />

In your Fragment Java class, you need to have the following to handle the Button's click event:

public class DetailFragment extends Fragment 
    implements OnClickListener 
    Button btn;

    public View onCreateView(LayoutInflater inflater,
    ViewGroup container, Bundle savedInstanceState)
        View view = inflater.inflate(
            R.layout.activity_detail, container, false);
        btn = (Button) view.findViewById(;

        return view;

    public void onClick(View v) {
            "Button is clicked!", Toast.LENGTH_LONG).show();


No comments: