android - 以编程方式触发 Android 中的操作栏菜单项

标签 android android-actionbar selection android-actionmode actionmode

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

我想加载此 Activity 。因此,我尝试以编程方式调用刷新图标项单击:

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

我在创建菜单后调用上面的方法。

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

这是我的:

 @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);
            }
        }
    }
}

是否可以通过编程方式调用菜单项?如果是怎么办?

谢谢!

最佳答案

只需执行 findViewById(R.id.action_Refresh).callOnClick();

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

关于android - 以编程方式触发 Android 中的操作栏菜单项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26015424/

相关文章:

android - 如何将数组转换为可观察的

android - 使用 Material Design 主题进行 fragment 隔离测试

java - Android onTouchEvent坐标跳转

javascript - 使用 javascript 选择要在网页中剪辑的元素

android - 将 EditText/TextView 置于 MapView Android 之上

android - Actionbar 'action button' 以编程方式禁用/启用?

android - 搜索 View 关闭图标显示为禁用而不是白色

java - Android Studio 1.1.0 您需要使用 Theme.AppCompat 主题(或后代)美眉

ios - 如何隐藏 UITableView 中某些单元格的多选编辑 GUI?

database - 在数据库中存储多选值的任何好方法?