Connecting android fragment events
Android UI Fragments look like a great way to build re-usable elements within an app, but they don’t work exactly as expected out of the box (well, exactly is I expected – but that could be a lack of experience with android):
After defining an onClick event on a button within my fragment:
<Button android:id="@+id/add_goal_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_create"
android:onClick="addGoal" />
I’d expected this event to be routed directly to my fragment class without the containing Activity class needing to know about it – but instead, the addGoal() method is expected on the containing Activity instead.
To connect the fragment event directly to a click handler on the fragment class (so the view doesn’t need to be handling the fragment events, you can do the following instead (thanks Brill Pappin):
public class NewGoalFragment extends Fragment {
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View fragmentView = inflater.inflate(R.layout.fragment_new_goal,
container, false);
...
Button addGoalButton = (Button) fragmentView.findViewById(R.id.add_goal_button);
addGoalButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
// Pass the fragmentView through to the handler
// so that findViewById can be used to get a handle on
// the fragments own views.
addGoal(fragmentView);
}
});
return fragmentView;
}
public void addGoal(View view) {
EditText newGoal = (EditText) view.findViewById(R.id.new_goal);
...
}