在Android中以编程方式触发操作栏菜单项

The*_*Man 4 android selection android-actionbar actionmode android-actionmode

我在栏上有菜单项的操作栏.当我点击刷新图标时,我有显示进度条的方法.

我想加载这个活动.因此,我尝试以编程方式单击调用刷新图标项:

onOptionsItemSelected(menu.findItem(R.id.action_Refresh)); 
Run Code Online (Sandbox Code Playgroud)

我在创建菜单后调用上面的内容.

但这会在加载我的数据时给出空指针异常.如果我点击刷新按钮它工作正常,但如果我以编程方式调用它我会收到错误.

这是我有的:

 @Override
public boolean onCreateOptionsMenu(Menu menu) 
{
    this.optionsMenu = menu;
    getMenuInflater().inflate(R.menu.main, menu);

    onOptionsItemSelected(menu.findItem(R.id.action_Refresh));

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) 
{
    switch (item.getItemId()) 
    {
    case R.id.action_about:
        aboutapp();
        return true;

    case R.id.action_Refresh:
        Log.e("REfressh","Clicked");
        Mapsthree.refreshValue = 0;
        timer = new Timer();
        timerMethod();
        setRefreshActionButtonState(true);
        displayView(1);
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

private void timerMethod()
{
    timer.scheduleAtFixedRate(new TimerTask() 
    {
        @Override
        public void run() 
        {
            updateProgressBar();
        }

    }, 0, 800);
}

private void updateProgressBar() 
{
    runOnUiThread(new Runnable() 
    {
        public void run() 
        {
            if (Maps.refreshValue == 1)
            {
                setRefreshActionButtonState(false);
                timer.purge();
                timer.cancel();
            }
        }
    });
}

public void setRefreshActionButtonState(final boolean refreshing) 
{
    if (optionsMenu != null) 
    {
        final MenuItem refreshItem = optionsMenu.findItem(R.id.action_Refresh);
        if (refreshItem != null) 
        {
            if (refreshing) 
            {
                refreshItem.setActionView(R.layout.actionbar_indeterminate_progress);
            } 
            else 
            {
                refreshItem.setActionView(null);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

是否可以以编程方式调用菜单项?如果是这样的话?

谢谢!

Ped*_*ira 6

做就是了 findViewById(R.id.action_Refresh).callOnClick();

要么

findViewById(R.id.action_Refresh).performClick();