简体   繁体   English

Android操作栏菜单项

[英]Android actionbar menu item

I have a item menu (sorting list) in my actionbar that I have to set its visibility to VISIBLE / GONE (depending on the list size -> empty or not). 我的操作栏中有一个项目菜单(排序列表),我必须将其可见性设置为VISIBLE / GONE(取决于列表大小 - >是否为空)。

So what I need is to check if listview is empty or not and set the visibility of that menu item accordingly, and I managed to came up with some code to do that (check listview size in onCreateOptionsMenu and set menu item visibility), but the problem is that the list can change its content both from same activity or from another, leaving me no option (IMO) than to check again listview size and set visiblity in onResume(). 所以我需要的是检查listview是否为空并相应地设置该菜单项的可见性,我设法想出一些代码(检查onCreateOptionsMenu中的listview大小并设置菜单项可见性),但是问题是列表可以从相同的活动或从另一个活动更改其内容,让我没有选项(IMO),而不是再次检查列表视图大小并在onResume()中设置visiblity。

Here comes next problem: setting visibility of that item in onResume(), will throw a NPE, as I don't yet have that MenuItem initialized (onCreateOptionsMenu is called after onResume). 下一个问题是:在onResume()中设置该项的可见性,将抛出一个NPE,因为我还没有初始化MenuItem(在onResume之后调用onCreateOptionsMenu)。 Any ideas on how to solve this situation would be appreciated. 如何解决这种情况的任何想法将不胜感激。

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    getSupportMenuInflater().inflate(R.menu.main, menu);

    /*
     * initialize sortMenuItem so it can be used for turning visibility
     * on/off in onResume()
     */
    sortMenuItem = menu.findItem(R.id.menu_sort);

    return true;
}

@Override
public void onResume() {
    super.onResume();

    boolean isListEmpty = mInterviewsList.isEmpty();

    Log.d(LOG_TAG, "sortMenuItem is null? " + (sortMenuItem == null)); 
            // sortMenuItem is indeed null

    sortMenuItem.setVisible(isListEmpty);
    sortMenuItem.setEnabled(!isListEmpty);
    this.invalidateOptionsMenu();

}

您可以在onCreateOptionsMenu中动态添加sortMenuItem,具体取决于您的列表视图大小,如果您使用(google ActionBar compat lib)或类似方法,则可以在onResume中调用supportInvalidateOptionsMenu()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM