我使用的是原生ActionBar和ShareActionProvider。
我的活动中有一段代码会在四秒钟内隐藏ActionBar:
Handler hideUIHandler = new Handler();
hideUIHandler.postDelayed(new Runnable() {
public void run() {
getActionBar().hide();
}
}, 4000);
不幸的是hideUIHandler
隐藏了ActionBar,即使我点击了"分享"项目,以查看由ShareActionProvider提供的菜单。
在这种情况下,我不想隐藏ActionBar。我该怎么办?
答案 0 :(得分:2)
您可以覆盖Activity.onMenuOpened
和Activity.onPanelClosed
以确定何时显示溢出菜单或其他子菜单,例如ShareActionProvider
。这是一个例子:
/** True if an options menu has been opened, false otherwise */
private boolean mMenuOpened;
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
mMenuOpened = true;
return super.onMenuOpened(featureId, menu);
}
@Override
public void onPanelClosed(int featureId, Menu menu) {
super.onPanelClosed(featureId, menu);
mMenuOpened = false;
}
<强>替代地强>
ActivityChooserView
可以检查ActivityChooserView.isShowingPopup,但您必须继承ShareActionProvider
并通过反射调用它,因为隐藏了ActivityChooserView
类。
以下是一个例子:
<强> AccessibleShareActionProvider 强>
/**
* A subclass of {@link ShareActionProvider} that uses reflection to invoke
* <p>
* <code>android.widget.ActivityChooserView.isShowingPopup</code>
* <p>
*/
public class AccessibleShareActionProvider extends ShareActionProvider {
/** The action view created for {@link ShareActionProvider} */
private View mActivityChooserView;
/**
* Constructor for <code>AccessibleShareActionProvider</code>
*
* @param context The {@link Context} to use
*/
public AccessibleShareActionProvider(Context context) {
super(context);
}
/**
* {@inheritDoc}
*/
@Override
public View onCreateActionView(MenuItem forItem) {
mActivityChooserView = super.onCreateActionView(forItem);
return mActivityChooserView;
}
/**
* @return True if showing, false if already dismissed
*/
public boolean isShowingPopup() {
try {
final Class<?> acv = Class.forName("android.widget.ActivityChooserView");
final Method isShowingPopup = acv.getMethod("isShowingPopup", new Class[] {});
return (boolean) isShowingPopup.invoke(mActivityChooserView, new Object[] {});
} catch (final Exception ignored) {
// Nothing to do
}
return false;
}
}
您的MenuItem
<item
android:id="@+id/menu_item_share"
android:actionProviderClass="your_path_to.AccessibleShareActionProvider"
android:showAsAction="ifRoom"
android:title="@string/share"/>
在Activity
private Handler mHandler = new Handler();
private AccessibleShareActionProvider mShareProvider;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
...
final MenuItem item = menu.findItem(R.id.menu_item_share);
mShareProvider = (AccessibleShareActionProvider) item.getActionProvider();
...
return super.onCreateOptionsMenu(menu);
}
private final Runnable mHideActionBar = new Runnable() {
@Override
public void run() {
// If the ShareActionProvider is showing, delay for 4 seconds
if (mShareProvider.isShowingPopup()) {
mHandler.removeCallbacksAndMessages(null);
mHandler.postDelayed(mHideActionBar, 4000);
return;
}
getActionBar().hide();
}
};