Something-driven development

Software development thoughts around Ubuntu, Python, Golang and other tools

Connecting android fragment events

leave a comment »

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: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 {
	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(;
		addGoalButton.setOnClickListener(new OnClickListener() {
			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.
		return fragmentView;
    public void addGoal(View view) {    	
    	EditText newGoal = (EditText) view.findViewById(;

Written by Michael

January 1, 2013 at 6:21 pm

Posted in android

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 105 other followers

%d bloggers like this: