Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

android - Add onOptionsItemSelected calling in Fragment

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_filter) {
        FragmentManager fm = getSupportFragmentManager();
        if (userType.equals("?? Arayan"))
            filterDialogTitle = "?? ?lanlar? Filtre";
        else if (userType.equals("Hizmet Arayan"))
            filterDialogTitle = "Hizmet ?lanlar? Filtre";
        FilterDialogFragment editNameDialogFragment = FilterDialogFragment.newInstance(filterDialogTitle);
        editNameDialogFragment.show(fm, "fragment_edit_name");
        return true;
    }

    return super.onOptionsItemSelected(item);
}

I added in Fragment, but i didn' t called, if i add in MainActivity, it works but i want call in Fragment. How can i do this ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In Fragment you have to call setHasOptionsMenu(true)

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    ...
}

Then suppose you have to handle menu_item_to_handle_in_fragment item click

For Fragment class

  @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

        case R.id.menu_item_to_handle_in_fragment:
            // Do onlick on menu action here
            return true;
        }
    return false;
}

For Activity class

 @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {

            case R.id.menu_item_to_handle_in_fragment:
                return false;
            }
        return false;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...