Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Action bar item click handler in fragment

I have a simple 2 activity application. The main activity populates a listFragment, and the second activity populates a fragment with fields to add a custom object (list items) to the main activity.

In the second activity I have a "save" icon in the action bar. I'm trying to figure out how to listen for this button click in the fragment, so I can package up the textFields and pass it back to the activity via the interface.

I tried to override onOptionItemSelectedbut it doesn't ever hit. How would I handle this?

like image 327
ENG618 Avatar asked Nov 28 '22 20:11

ENG618


1 Answers

Okay, so the trick is in the fragments onCreate method, you have to call

setHasOptionsMenu(true);

then all you have to do is override the onOptionsItemSelected in the fragment, and handle the action bar click there!!

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_save : {
            Log.i(TAG, "Save from fragment");
            return true;
        }
    }
    return super.onOptionsItemSelected(item);
}
like image 165
ENG618 Avatar answered Dec 11 '22 05:12

ENG618