导航抽屉 - 慢慢为菜单项设置动画

时间:2014-12-19 08:53:13

标签: android navigation-drawer android-ui

我已经使用this教程实施了DrawerLayout,一切正常。

@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值设置动画。

1 个答案:

答案 0 :(得分:1)

  

我想要在打开导航时慢慢看不见它   抽屉

实现此目的的一个非常简单的方法是使用View.findViewsWithText。这是一个简单的例子:

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