活动没有选项菜单

时间:2016-01-19 06:17:20

标签: android robolectric

我试图使用 Robolectric 模拟点击菜单项中的菜单项,使用以下代码

ShadowActivity shadowActivity = Shadows.shadowOf(activity);
shadowActivity.clickMenuItem(R.id.action_logout);

但它给了我一个错误:

java.lang.RuntimeException: Activity does not have an options menu! Did you forget to call super.onCreateOptionsMenu(menu)

活动代码:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home_layout);
    overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);

    ButterKnife.bind(this);

    setToolbarIcons();
    toolbar.inflateMenu(R.menu.menu_splash);
    toolbar.setOnMenuItemClickListener(this);
}


@Override
public boolean onMenuItemClick(MenuItem item) {

    int id = item.getItemId();
    if (id == R.id.action_logout){
        //Doing Some task here...
        return true;
    }
    return false;
}

你能帮我解决错误吗?

2 个答案:

答案 0 :(得分:0)

问题似乎是,您没有将工具栏设置为supportActionbar / ActionBar。

我从未见过这样的工具栏膨胀,但通常是这样做的:

public class MyActivity extends AppCompatActivity {

    @Bind(R.id.toolbar) Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_login);            
        butterKnife.bind(this);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.actions_myactivity, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //handle clicked menuItem

        return super.onOptionsItemSelected(item);
    }
}

因为你的错误是:

Activity does not have an options menu!

此外,Testmethod应该是这样的

@Test
public void clickOnMenuItem(){
    ShadowActivity shadowActivity = Shadows.shadowOf(activity);
    Menu menu =  mToolbar.getMenu();
    shadowActivity.onCreateOptionsMenu(menu);
    shadowActivity.clickMenuItem(R.id.action_logout);
}

我认为这是要走的路!

答案 1 :(得分:0)

活动类中进行更改并深入挖掘 Robolectric 工具栏之后,我在测试类中做了一些更改,这是工作正常

@Test
public void clickOnMenuItem(){
    ShadowActivity shadowActivity = Shadows.shadowOf(activity);
    Menu menu =  mToolbar.getMenu();
    shadowActivity.onCreateOptionsMenu(menu);
    shadowActivity.clickMenuItem(R.id.action_logout);
}