编程语言
首页 > 编程语言> > 在Android中以编程方式触发操作栏菜单项

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

作者:互联网

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

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

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

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

谢谢!

解决方法:

你为什么要从onCreateOptionsMenu调用它?

您可以根据要求编写用于加载onCreate或onResume方法的代码:

@Override
protected void onCreate(Bundle arg0) {

    super.onCreate(arg0);

    //whatever you are doing

    //now code for refresh

    Log.e("REfressh","First time");
    Mapsthree.refreshValue = 0;
    timer = new Timer();
    timerMethod();
    setRefreshActionButtonState(true);
    displayView(1);
}

标签:android,android-actionbar,selection,android-actionmode,actionmode
来源: https://codeday.me/bug/20190717/1490469.html