本文介绍了导航抽屉-缓慢设置菜单项的动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经使用这个教程,一切正常.
I've implemented a DrawerLayout
with this tutorial and everything works fine.
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
onPrepareOptionsMenu
只需一次切换菜单可见性即可.但是,我想在抽屉滑动时慢慢设置菜单项的Alpha值的动画.
onPrepareOptionsMenu
simply toggles the menu visibility in one shot. But I'd like to slowly animate the alpha value of my menu items as the drawer slides.
推荐答案
实现此目标的一种非常简单的方法是利用 View.findViewsWithText
.这是一个简单的示例:
A really simple way to accomplish this is to utilize View.findViewsWithText
. Here's a quick example:
public class YourActivity extends Activity {
/** Contains our {@linkplain MenuItem menu items} */
private final ArrayList<View> mMenuItems = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
// Initialize the drawer
final DrawerLayout drawer = ...;
drawer.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
animateMenuItems(slideOffset);
}
});
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
// Add some dummy items
menu.add("queue")
.setIcon(R.drawable.ic_menu_queue)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add("search")
.setIcon(R.drawable.ic_menu_search)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
// Collect the menu items
final ViewGroup decor = (ViewGroup) getWindow().getDecorView();
decor.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// Remove any installed layout listeners
decor.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// Find each MenuItem
findMenuItems(decor, menu);
}
});
return true;
}
/** Used to traverse the decor hierarchy to locate all the menu items */
private void findMenuItems(ViewGroup decor, Menu menu) {
final int size = menu.size();
for (int i = 0; i < size; i++) {
final CharSequence title = menu.getItem(i).getTitle();
if (!TextUtils.isEmpty(title)) {
decor.findViewsWithText(mMenuItems, title, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
}
}
}
/** Used to animate each {@link MenuItem} based on the offset */
private void animateMenuItems(float slideOffset) {
for (final View view : mMenuItems) {
if (view != null) {
view.setAlpha(1f - slideOffset);
}
}
}
}
结果
http://www.gfycat.com/BriskLiquidGaur
这篇关于导航抽屉-缓慢设置菜单项的动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!