以编程方式隐藏/显示上下文操作栏 [英] Hiding/showing the contextual action bar programmatically
问题描述
我的用例:
我有一个以 ViewPager
作为唯一视图元素的活动,为其三个页面设置了三个 Fragment
(使用 FragmentPagerAdapter
>).其中一个片段是 ListFragment
,而另外两个常规 Fragment
包含一些信息图表.
I have an activity with a ViewPager
as its only view element, set up with three Fragment
s for its three pages (using a FragmentPagerAdapter
). One of these fragments is a ListFragment
, while the other two regular Fragment
s containing some infographics.
ListFragment
中的列表允许检查"元素,检查元素会显示上下文操作栏,显示对选定/选中的项目可能执行的操作列表.
The list in the ListFragment
allows "checking" elements, and checking elements brings up the contextual action bar, presenting a list of actions possible on the selected/checked items.
我的问题:
当我选择几个列表项时,CAB 就会出现.但是当我切换页面时,CAB 保持可见,显示操作.更糟糕的是,ViewPager
似乎有时会破坏列表片段的视图 - 因此选择操作会抛出 "java.lang.IllegalStateException: Content view not yet created"
例外.
When I select a couple of list items, the CAB shows up. But when I switch pages, the CAB stays visible, presenting the actions. To make matters worse, the ViewPager
seems to sometimes destroy the view of the list fragment - hence selecting the actions throws a "java.lang.IllegalStateException: Content view not yet created"
exception.
我的问题:
- 当用户离开
ListFragment
页面时,如何让 CAB 消失? - (可选)当
ListFragment
返回且某些项目仍处于检查状态时,如何让 CAB 重新出现.
- How do I get the CAB to disappear when the user moves away from the
ListFragment
page? - (optional) How do I get the CAB to reappear when the
ListFragment
back is and some items are still checked.
推荐答案
你需要先添加一个 ViewPager.OnPageChangeListener
和 ViewPager.OnPageChangeListener
到你的 viewPager
.
You need to first add a ViewPager.OnPageChangeListener
with ViewPager.OnPageChangeListener
to your viewPager
.
在 onPageSelected 方法中调用 ListFragment
中的方法来关闭 CAB.
In the onPageSelected method call a method in your ListFragment
to dismiss your CAB.
要获取当前的活动片段,您可以使用它的标签.可以用这种方法计算标签:
To get the current active fragment you can use it's tag. The tag can be computated with this method:
private static String makeFragmentName(int viewId, int index) {
return "android:switcher:" + viewId + ":" + index;
}
其中viewId是viewpager的id并索引标签索引(位置)
where viewId is the id of the viewpager and index the tab index (position)
这篇关于以编程方式隐藏/显示上下文操作栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!