Reputation: 5835
I am trying to achieve the effect of a piece of paper coming out of a slot with a list of items on it. I came up with one approach but as I am working on it I can't keep on thinking there must be a better way.
My approach:
<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>
Animation code:
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);
My question:
Is there a better way? I am not asking a suggestive question I merely want to know if there is a built in function of some sort that will make a view appear gradually from a set point.
Upvotes: 1
Views: 80
Reputation: 3253
It seems like you are trying to achieve a simple translation animation. One way of approaching this situation is to use the Property Animation Api introduced in Api level 10 (and generously backported to api level 1 with Jake Wharton's nine old androids library).
A simple example could be the following
ObjectAnimator.ofFloat(theViewObject, "translationY", -theViewObject.getHeight(), 0)
.setDuration(2000) // 2 seconds
.start();
sometimes, calls like getHeight()
or getRight()
etc, return 0. This is because the view hasn't actually been drawn yet. To accomodate for this you can register a callback to know when the view has been drawn.
// 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);
}
}
});
}
Upvotes: 1