onClick inside fragment called on Activity

Solution 1:

I spoke to some googlers @ #adl2011 - they recognize the problem and perhaps there will be a fix of that in the future. Until then - one should use .setOnClick in the Fragment.

Solution 2:

The problem is that when layout's are inflated it is still the hosting Activity that is receiving the button clicks, not the individual 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;
        }
    }
}

Then problem is gone.