我正在使用 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
中使用百分比值而不是 getXFraction
和 setXFraction
您必须添加 getYFraction
和 setYFraction
这样的方法
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/