将ListView设置为视图的动画

时间:2014-04-30 13:32:10

标签: android

我正在努力实现从一个带有项目列表的插槽中出来的一张纸的效果。我提出了一种方法,但在我努力的时候,我不能继续思考必须有更好的方法。

我的方法:

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    >
    <ListView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/orderDetailListView">

    </ListView>

</LinearLayout>

动画代码:

final int newMargin = <some value>;
Animation a = new Animation() {

@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
    LayoutParams params = listView.getLayoutParams();
    params.leftMargin = (int)(newMargin * interpolatedTime);
    yourView.setLayoutParams(params);
    }
};

listView.startAnimation(a)的

我的问题:

有更好的方法吗?我不是在问一个暗示性的问题,我只是想知道是否有某种类型的内置函数会使视图从设定点逐渐出现。

Image from yplan app

1 个答案:

答案 0 :(得分:1)

您似乎正在尝试实现简单的翻译动画。处理这种情况的一种方法是使用Api级别10中引入的Property Animation Api(并且与Jake Wharton的nine old androids库慷慨地向后移植到api级别1。)

一个简单的例子可能是以下

ObjectAnimator.ofFloat(theViewObject, "translationY", -theViewObject.getHeight(), 0)
        .setDuration(2000) // 2 seconds
        .start();

有时,getHeight()getRight()等调用会返回0.这是因为视图尚未实际绘制。为了适应这种情况,您可以注册回调以了解何时绘制视图。

// Listen for when the view has been drawn so we can get its dimensions
final ViewTreeObserver viewTreeObserver = theViewObject.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
    viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @SuppressWarnings("deprecation")
        @Override
        public void onGlobalLayout() {

            ObjectAnimator.ofFloat(
                    theViewObject, "translationY", -theViewObject.getHeight(), 0)
                    .setDuration(2000) // 2 seconds
                    .start();

            // stop listening for updates to the view so that this is only called once
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                viewTreeObserver.removeOnGlobalLayoutListener(this);
            } else {
                viewTreeObserver.removeGlobalOnLayoutListener(this);
            }
        }
    });
}
相关问题