在AppCompatActivity中使用setDisplayHomeAsUpEnabled在片段中调用onOptionsItemSelected

时间:2016-10-05 13:51:24

标签: android fragment appcompatactivity

我通过所有类似的问题和答案整天搜索,在stackoverflow中,但没有发现为什么它不起作用

这里有我的代码摘录

片段:

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
    setHasOptionsMenu(true);
    actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
    actionBar.setTitle("Portfolio");
    updateGallery();
    return rootView;
}


    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
}

    public void updateGallery() {
    if (activeAlbum>0) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    } else {
        actionBar.setDisplayHomeAsUpEnabled(false);
    }
 ......
}

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        default:
            break;
    }
    return false;
}

MainActivity:

public class MainActivity extends AppCompatActivity {...}

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

....

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);


......
 }


    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_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

onOptionsItemSelected既不在MainActivity也不在Fragment

中触发

1 个答案:

答案 0 :(得分:1)

碎片必须声明它们可以提供选项。看看这里:

https://developer.android.com/reference/android/app/Fragment.html#setHasOptionsMenu(boolean)

我认为您只需要在片段的onCreateView()中调用setHasOptionsMenu(true)。