如何在 Android 的 ObjectAnimator 中给出百分比值

新手上路,请多包涵

我正在使用 objectAnimator 在 Android 中从下到上为按钮设置动画。现在我正在使用下面的代码

ObjectAnimator transAnimation = ObjectAnimator.ofFloat(button,"translationY",0,440);
        transAnimation.setDuration(440);
        transAnimation.start();

我也试过下面的示例代码。但是问题依然存在

ObjectAnimator transAnimation = ObjectAnimator.ofFloat(loginLayout, "translationY",0f,0.8f);
                    transAnimation.setDuration(480);
                    transAnimation.start();

它在大屏幕设备上运行良好。但是当涉及到小屏幕设备时,它就会消失在屏幕上。无论屏幕尺寸如何,我都想将其保留在屏幕顶部。我想我必须给出百分比值(比如 0% 到 100% 或 0 到 100%p)。所以我的问题是如何在 Android 的 objectAnimator 中以百分比形式给出值。我还注意到一件事,这个 objectAnimator 只在 HoneyComb 中引入。那么是否有任何向后兼容的库可以在低版本中运行它。谁能指导我找到解决方案。

我还尝试扩展 View 并为 offset() 中的属性编写 getter 和 setter。它仍然没有完全移动到屏幕顶部。这是我使用的代码。

 @SuppressLint("NewApi") public float getXFraction()
    {
        int width = context.getWindowManager().getDefaultDisplay().getHeight();
        return (width == 0) ? 0 : (getY());
    }

    @SuppressLint("NewApi") public void setXFraction(float xFraction) {
        int width = context.getWindowManager().getDefaultDisplay().getWidth();
        setY((width > 0) ? (width) : 0);
    }

提前致谢

原文由 Sanal Varghese 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 815
1 个回答

要在 Honeycomb 之前的设备上使用 ObjectAnimatorNineOldAndroids 库添加到您的项目并更改导入以使用 com.nineoldandroids.animation.ObjectAnimator

To use percentage values in ObjectAnimator instead of getXFraction and setXFraction you have to add getYFraction and setYFraction methods like这个

public float getYFraction() {
    final WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
    int height = wm.getDefaultDisplay().getHeight();
    return (height == 0) ? 0 : getY() / (float) height;
}

public void setYFraction(float yFraction) {
    final WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
    int height = wm.getDefaultDisplay().getHeight();
    setY((height > 0) ? (yFraction * height) : 0);
}

然后你可以像这样创建xml文件 project-folder/res/animator/move_bottom.xml

 <?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500"
    android:propertyName="yFraction"
    android:valueFrom="0"
    android:valueTo="0.8"
    android:valueType="floatType" />

或者在代码中创建动画

final LoginLayout loginLayout = (LoginLayout) findViewById(R.id.login_layout);
final ObjectAnimator oa = ObjectAnimator.ofFloat(loginLayout, "yFraction", 0f, 0.8f);
oa.start();

原文由 vasart 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题