未调用菜单片段类

时间:2013-11-30 18:38:29

标签: java android android-fragments

我希望通过片段控制我的菜单,以便最小化代码 复制。我遇到的问题是活动类在调试时接收调用,但它不会继续到Fragment类。课程如下所示。

我认为Fragment'参与'布局生命周期 从Fragment继承时。我在这里缺少什么?

SomeActivity.java

public class SomeActivity extends Activity {

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActionBar().show();
        setContentView(R.layout.a);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    public void chooseLanguage(View view) {
        Intent intent = new Intent(this, AActivity.class);
        startActivity(intent);
    }
}

MenuFragment.java

public class MenuFragment extends Fragment {
  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
        menuInflater.inflate(R.menu.main, menu);
        super.onCreateOptionsMenu(menu, menuInflater);
    }

    public void startActivity(Class classs) {
        Intent intent = new Intent(getActivity(), classs);
        startActivity(intent);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        switch (menuItem.getItemId()) {
            case R.id.a:
                startActivity(AActivity.class);
                return true;
            case R.id.b:
                startActivity(BActivity.class);
                return true;
            case R.id.c:
                startActivity(CActivity.class);
                return true;
            case R.id.d:
                startActivity(DActivity.class);
                return true;
            default:
                return super.onOptionsItemSelected(menuItem);
        }
    }
}

2 个答案:

答案 0 :(得分:0)

来自Activity的{​​{3}}的文档:

  

您必须返回true才能显示菜单;如果你返回false,它将不会显示。

因此请确保返回true而不是

return super.onCreateOptionsMenu(menu);

答案 1 :(得分:0)

所以解决方案包括

在活动的onCreate

中添加片段

getFragmentManager().beginTransaction().add(new MenuFragment(), "Menu fragment").commit();

然后,根据文档

,Activity中的onOptionsItemSelected应该返回false

boolean Return false to allow normal menu processing to proceed, true to consume it here.

https://developer.android.com/reference/android/app/Activity.html#onOptionsItemSelected(android.view.MenuItem)