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

标签 android android-animation objectanimator

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

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

I have also tried with sample code below. But still the problem exists

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);
    }

提前致谢

最佳答案

要在预Honeycomb 设备上使用ObjectAnimator,请添加NineOldAndroids库到您的项目并更改您的导入以使用 com.nineoldandroids.animation.ObjectAnimator

要在 ObjectAnimator 中使用百分比值而不是 getXFractionsetXFraction 您必须添加 getYFractionsetYFraction 这样的方法

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();

关于android - 如何在 Android 的 ObjectAnimator 中给出百分比值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15919587/

相关文章:

android - CardView 在 RotationY > 60 时显示伪像

android - 动画期间点击 View 没有反应

java - SQLite 如果存在现有数据则跳过或覆盖

android - 构建 android ICS 时头文件中的歧义

android - 在 android 中使用 rabbitmq 进行聊天

具有scaleType centerCrop的Android ImageView平移动画

Android 8.0 蓝牙设备后台服务

android - Android中的脉动按钮动画

android - Drawable 对象上的 ObjectAnimator

java - Android ObjectAnimator 与 ViewPropertyAnimator