使用AppCompat-v7隐藏工具栏时出错

时间:2015-05-05 09:11:41

标签: android android-support-library android-toolbar

我试图隐藏文本更改侦听器中的工具栏

public void onTextChanged(CharSequence s, int start, int before, int count) {
    toolbar.animate()
        .translationY(-toolbar.getBottom())
        .setInterpolator(new AccelerateInterpolator())
        .start();
}

这个解决方案可以在更高级别的api上完美运行(在kitkat上成功运行)。但是我在运行具有api级别10的设备时遇到以下错误。

  

java.lang.NoSuchMethodError:android.support.v7.widget.Toolbar.animate

布局xml部分是

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:background="#ff6d7fe2"
    app:contentInsetEnd="0dp">
</android.support.v7.widget.Toolbar>

我没有将工具栏设置为支持操作栏。为什么即使使用android.support.v7.widget.Toolbar我也收到此错误?

2 个答案:

答案 0 :(得分:1)

此错误是因为您使用ViewPropertyAnimator方法toolbar.animate()。这只与12级以上的API级别兼容。因此,您可以使用JakeWharton的NineOldAndroid库使其与低于12的API兼容。

答案 1 :(得分:1)

Toolbar只是一个视图,animate是在v10之后引入的View上的方法 - 因此当您尝试在v10设备上调用它时它不存在并崩溃

您可以使用

ViewCompat.animate(toolbar).translationY(-toolbar.getBottom()).setInterpolator(new AccelerateInterpolator()).start();

但这不会做任何动画前ICS。您可以使用NineOldAndroid作为Sajal建议,将动画放在旧设备上,或使用旧动画框架为视图设置动画。