关闭时加快'导航抽屉'动画速度?

时间:2013-10-18 23:49:19

标签: android

实现并按预期工作,因此确实没有值得发布的代码,只是想知道是否有人有加快抽屉打开和关闭所需时间的经验?例如,YouTube应用程序要快得多!

7 个答案:

答案 0 :(得分:23)

您绝对可以调整动画的持续时间,但它需要您复制支持库中的类,然后相应地进行编辑。

<强> ViewDragHelper

The duration is determined here in ViewDragHelper

然后在ViewDragHelper.smoothSlideViewTo is called

时应用于DrawerLayout

您需要创建一个传递持续时间参数的ViewDragHelper.forceSettleCapturedViewAt修改版本。

forceSettleCapturedViewAt(... int duration)

然后创建您的ViewDragHelper.smoothSlideViewTo版本。

public boolean smoothSlideViewTo(... int duration) {
        ...
        return forceSettleCapturedViewAt(... int duration);
    }

<强> DrawerLayout

接下来,您需要修改DrawerLayout.closeDrawerDrawerLayout.closeDrawers以匹配新的ViewDragHelper修改。

<强> ActionBarDrawerToggle

您还必须复制ActionBarDrawerToggleActionBarDrawerToggleHoneycomb。这些文件不需要任何编辑。

答案 1 :(得分:7)

加速动画并等待它完成的另一种方法是首先避免动画:只需在不调用startActivity()的情况下调用closeDrawer()即可。虽然您没有看到抽屉关闭,但活动过渡动画仍然提供了非常好的效果,并且它立即发生,无需等待抽屉关闭动画首先完成稳定,没有波动,以及更短的感知延迟

详细

(如果您只想查看代码,可以跳过此解释。)

要完成这项工作,您需要一种在使用后退按钮导航回活动时关闭抽屉而无需任何关闭动画的方法。 (不调用closeDrawer()将使抽屉在该活动实例中保持打开;相对浪费的解决方法是在导航时强制将活动强制为recreate(),但是可以在不执行此操作的情况下解决此问题。)如果您在导航后返回,也需要确保只关闭抽屉,而不是在方向更改后关闭抽屉,但这很容易。

虽然从closeDrawer()调用onCreate()会使抽屉在没有任何动画的情况下关闭,但onResume()也是如此。从closeDrawer()调用onResume()将使用用户暂时可见的动画关闭抽屉。 DrawerLayout没有提供任何方法来关闭没有动画的抽屉,但可以添加一个。

正如@syesilova指出的那样,关闭抽屉实际上只是将它从屏幕上滑下来。因此,您可以通过将抽屉直接移动到“关闭”位置来有效地跳过动画。翻译方向将根据重力(无论是左侧还是右侧抽屉)而有所不同,确切位置取决于抽屉与其所有儿童一起布置后的大小。

然而,仅仅移动它是不够的,因为DrawerLayout在扩展LayoutParams中保留了一些内部状态,用于了解抽屉是否打开。如果你只是将抽屉移开屏幕,它就不会知道它已关闭,这将导致其他问题。 (例如,抽屉将在下一个方向更改时重新出现。)

由于您正在将支持库编译到您的应用中,因此您可以在android.support.v4.widget包中创建一个类以访问其默认(包私有)部分,或者在不复制的情况下扩展DrawerLayout超过它需要的任何其他类。这也将减少更新代码的负担,以及将来对支持库的更改。 (最好尽可能将代码与实现细节隔离开来。)您可以使用moveDrawerToOffset()移动抽屉,并设置LayoutParams以便它知道抽屉已关闭。

代码

这是跳过动画的代码:

// move drawer directly to the closed position
moveDrawerToOffset(drawerView, 0.f); 

/* EDIT: as of v23.2.1 this direct approach no longer works
         because the LayoutParam fields have been made private...
// set internal state so DrawerLayout knows it's closed
final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams();
lp.onScreen = 0.f;
lp.knownOpen = false;

invalidate();
/*/
// ...however, calling closeDrawer will set those LayoutParams
//    and invalidate the view.
closeDrawer(drawerView);
/**/

注意:如果您只是在不更改moveDrawerToOffset()的情况下致电LayoutParams,抽屉将在下一个方向更改时移回其打开位置。

选项1(使用现有的DrawerLayout)

这种方法为support.v4包添加了一个实用程序类,以便访问DrawerLayout中我们需要的包私有部分。

将此类放入/ src / android / support / v4 / widget /:

package android.support.v4.widget;

import android.support.annotation.IntDef;
import android.support.v4.view.GravityCompat;
import android.view.Gravity;
import android.view.View;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

public class Support4Widget {

    /** @hide */
    @IntDef({Gravity.LEFT, Gravity.RIGHT, GravityCompat.START, GravityCompat.END})
    @Retention(RetentionPolicy.SOURCE)
    private @interface EdgeGravity {}

    public static void setDrawerClosed(DrawerLayout drawerLayout, @EdgeGravity int gravity) {
        final View drawerView = drawerLayout.findDrawerWithGravity(gravity);
        if (drawerView == null) {
            throw new IllegalArgumentException("No drawer view found with gravity " +
                    DrawerLayout.gravityToString(gravity));
        }

        // move drawer directly to the closed position
        drawerLayout.moveDrawerToOffset(drawerView, 0.f); 

        /* EDIT: as of v23.2.1 this no longer works because the
                 LayoutParam fields have been made private, but
                 calling closeDrawer will achieve the same result.

        // set internal state so DrawerLayout knows it's closed
        final DrawerLayout.LayoutParams lp = (DrawerLayout.LayoutParams) drawerView.getLayoutParams();
        lp.onScreen = 0.f;
        lp.knownOpen = false;

        drawerLayout.invalidate();
        /*/
        // Calling closeDrawer updates the internal state so DrawerLayout knows it's closed
        // and invalidates the view for us.
        drawerLayout.closeDrawer(drawerView);
        /**/
    }
}

导航时在活动中设置一个布尔值,表示抽屉应该关闭:

public static final String CLOSE_NAV_DRAWER = "CLOSE_NAV_DRAWER";
private boolean mCloseNavDrawer;

@Override
public void onCreate(Bundle savedInstanceState) {
    // ...
    if (savedInstanceState != null) {
        mCloseNavDrawer = savedInstanceState.getBoolean(CLOSE_NAV_DRAWER);
    }
}

@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {

    // ...

    startActivity(intent);
    mCloseNavDrawer = true;
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putBoolean(CLOSE_NAV_DRAWER, mCloseNavDrawer);
    super.onSaveInstanceState(savedInstanceState);
}   

...并使用setDrawerClosed()方法关闭onResume()中没有动画的抽屉:

@Overrid6e
protected void onResume() {
    super.onResume();

    if(mCloseNavDrawer && mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
        Support4Widget.setDrawerClosed(mDrawerLayout, GravityCompat.START);
        mCloseNavDrawer = false;
    }
}

选项2(从DrawerLayout扩展)

这种方法扩展了DrawerLayout以添加setDrawerClosed()方法。

将此类放入/ src / android / support / v4 / widget /:

package android.support.v4.widget;

import android.content.Context;
import android.support.annotation.IntDef;
import android.support.v4.view.GravityCompat;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

public class CustomDrawerLayout extends DrawerLayout {

    /** @hide */
    @IntDef({Gravity.LEFT, Gravity.RIGHT, GravityCompat.START, GravityCompat.END})
    @Retention(RetentionPolicy.SOURCE)
    private @interface EdgeGravity {}

    public CustomDrawerLayout(Context context) {
        super(context);
    }

    public CustomDrawerLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomDrawerLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void setDrawerClosed(View drawerView) {
        if (!isDrawerView(drawerView)) {
            throw new IllegalArgumentException("View " + drawerView + " is not a sliding drawer");
        }

        // move drawer directly to the closed position
        moveDrawerToOffset(drawerView, 0.f); 

        /* EDIT: as of v23.2.1 this no longer works because the
                 LayoutParam fields have been made private, but
                 calling closeDrawer will achieve the same result.

        // set internal state so DrawerLayout knows it's closed
        final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams();
        lp.onScreen = 0.f;
        lp.knownOpen = false;

        invalidate();
        /*/
        // Calling closeDrawer updates the internal state so DrawerLayout knows it's closed
        // and invalidates the view for us.
        closeDrawer(drawerView);
        /**/
    }

    public void setDrawerClosed(@EdgeGravity int gravity) {
        final View drawerView = findDrawerWithGravity(gravity);
        if (drawerView == null) {
            throw new IllegalArgumentException("No drawer view found with gravity " +
                    gravityToString(gravity));
        }

        // move drawer directly to the closed position
        moveDrawerToOffset(drawerView, 0.f); 

        /* EDIT: as of v23.2.1 this no longer works because the
                 LayoutParam fields have been made private, but
                 calling closeDrawer will achieve the same result.

        // set internal state so DrawerLayout knows it's closed
        final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams();
        lp.onScreen = 0.f;
        lp.knownOpen = false;

        invalidate();
        /*/
        // Calling closeDrawer updates the internal state so DrawerLayout knows it's closed
        // and invalidates the view for us.
        closeDrawer(drawerView);
        /**/
    }
}

在您的活动布局中使用CustomDrawerLayout代替DrawerLayout

<android.support.v4.widget.CustomDrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    >

...当您离开时,在您的活动中设置一个布尔值,表示抽屉应该关闭:

public static final String CLOSE_NAV_DRAWER = "CLOSE_NAV_DRAWER";
private boolean mCloseNavDrawer;

@Override
public void onCreate(Bundle savedInstanceState) {
    // ...
    if (savedInstanceState != null) {
        mCloseNavDrawer = savedInstanceState.getBoolean(CLOSE_NAV_DRAWER);
    }
}

@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {

    // ...

    startActivity(intent);
    mCloseNavDrawer = true;
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putBoolean(CLOSE_NAV_DRAWER, mCloseNavDrawer);
    super.onSaveInstanceState(savedInstanceState);
}   

...并使用setDrawerClosed()方法关闭onResume()中没有动画的抽屉:

@Overrid6e
protected void onResume() {
    super.onResume();

    if(mCloseNavDrawer && mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
        mDrawerLayout.setDrawerClosed(GravityCompat.START);
        mCloseNavDrawer = false;
    }
}

我发现这是避免波动的最佳方法,没有任何长时间的感知延迟。

你可以几乎使用类似的技术来模拟在到达活动后关闭抽屉,通过传递意图中的值来告诉新活动打开其抽屉而没有动画来自{{ 1}}然后在活动布局完成后将其关闭动画,但在我的实验中,活动转换破坏了模拟的效果,因此您还需要禁用它。

答案 2 :(得分:2)

首先从下面链接下载sourcode文件

<强> DrawerLayout.java

并且

ViewDrawerHelper.java

  

粘贴你的应用程序包中的上述两个文件(或你想要的地方)并在你的活动中参考这个抽屉布局而不是android.support.v4.widget.DrawerLayout更改你的活动布局文件中的抽屉布局参考

现在调整

private static final int MAX_SETTLE_DURATION = 600; // ms
ViewDrawerHelper的

,加速只是增加值而向下只是减少值。

如果要在操作栏切换按钮上添加操作,则从下面链接下载

的源文件

<强> ActionBarDrawerToggle.java

<强> ActionBarDrawerToggleJellybeanMR2.java

<强> ActionBarDrawerToggleHoneycomb.java

  

并将上述文件粘贴到您的应用程序util包中(或您想要的位置)注意: - 确保每个新添加的文件的导入包引用应用程序项目中的文件,而不是android.support.v4中的文件.widget *;

如果以上链接无效,请添加http://

答案 3 :(得分:1)

如果你想立即强制消失左侧面板而没有任何动画,你可以简单地设置它的x值。当抽屉布局打开时,其左侧面板的x值变为0,当关闭时变为-1 *(其宽度)。因此,如果在打开时设置x值-2 *宽度,则左面板立即消失。当然,不要忘记在关闭后将x设置为-1 *宽度。 例如:

DisplayMetrics metrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(metrics);
//obtain left panel's width in px
private float mToggleStartX=-260*metrics.density; //260 is the width of left panel in dpi

//while drawer layout is opened, to disappear left panel
ll_drawerLayoutMenuPanel.setX(mToggleStartX*2); //ll_drawerLayoutMenuPanel is the left panel layout
mDrawerLayout.closeDrawers();

//don't forget reset x value in the onDrawerClosed method.
mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout,mainToolBar,R.string.drawer_open,R.string.drawer_close) {
    public void onDrawerClosed(View view) {
        super.onDrawerClosed(view);

        ll_drawerLayoutMenuPanel.setX(mToggleStartX);
    }
    ......
};

答案 4 :(得分:1)

这不允许您更改动画速度,但如果您想要立即关闭抽屉,则可以使用支持库v24中的新DrawerLayout.closeDrawer(int/View, bool)方法:

drawerLayout.closeDrawer(Gravity.LEFT, false);

答案 5 :(得分:0)

我相信您的问题的真正含义是,在我点击开始新活动的drawerlayout中的菜单后,如何让动画更顺畅地运行。
如果这是你问题的意思,我就是这样做的。

mLeftDrawer.ItemClick += delegate (object sender, Android.Widget.AdapterView.ItemClickEventArgs e)
        {
            // Mark that item is selected and ask redraw
            e.View.Selected = true;
            adapter.NotifyDataSetChanged();

            var handler = new Handler();
            handler.PostDelayed(new Java.Lang.Runnable(() =>
            {
                _mLeftDrawerLayout.CloseDrawers();

                // Here you should call your activity
            }), 100);

        };

答案 6 :(得分:-1)

按照以下

延迟关闭抽屉
@Override
public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.

        yourFunction();

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                drawer.closeDrawer(GravityCompat.START);
            }
        }, 100);
        return true;
}