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:

    <Button
       android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        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;

    @Override
    public View onCreateView(LayoutInflater inflater,
    ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.inflate(
            R.layout.activity_detail, container, false);
        
        btn = (Button) view.findViewById(R.id.button1);
        btn.setOnClickListener(this);       

        return view;
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(this.getActivity(), 
            "Button is clicked!", Toast.LENGTH_LONG).show();

    }

No comments: