Изменение размеров макетов программно (в виде анимации) - PullRequest
43 голосов
/ 15 ноября 2011

Я хочу изменить размеры некоторых макетов в своей Деятельности.

Вот код основного XML:

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/top"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:background="#3ee3e3" >
    </LinearLayout>

    <LinearLayout
        android:id="@+id/middle"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1">
    </LinearLayout>

    <LinearLayout
        android:id="@+id/bottom"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:background="#fe51e6" >
    </LinearLayout>
</LinearLayout>

Как видите, высота верхнего и нижнего макетов равна 0и средний макет охватывает все место.

Я хочу программно уменьшить средний размер макета, увеличив при этом размеры верхнего и нижнего макетов, пока все макеты не будут иметь одинаковую высоту.

Я хочу, чтобы он выглядел каканимация.

Как мне это сделать?

Спасибо

Ответы [ 3 ]

95 голосов
/ 17 ноября 2011

Я написал ResizeAnimation для аналогичной цели. Это просто, но дорого.

/**
 * an animation for resizing the view.
 */
public class ResizeAnimation extends Animation {
    private View mView;
    private float mToHeight;
    private float mFromHeight;

    private float mToWidth;
    private float mFromWidth;

    public ResizeAnimation(View v, float fromWidth, float fromHeight, float toWidth, float toHeight) {
        mToHeight = toHeight;
        mToWidth = toWidth;
        mFromHeight = fromHeight;
        mFromWidth = fromWidth;
        mView = v;
        setDuration(300);
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        float height =
                (mToHeight - mFromHeight) * interpolatedTime + mFromHeight;
        float width = (mToWidth - mFromWidth) * interpolatedTime + mFromWidth;
        LayoutParams p = mView.getLayoutParams();
        p.height = (int) height;
        p.width = (int) width;
        mView.requestLayout();
    }
}
4 голосов
/ 24 января 2014

В Honeycomb (Android 3.0) есть классы Animator и ObjectAnimator для более плавной анимации.

Прочтите здесь

Пример того, как анимировать перемещение группы видов (LinearLayout) с помощью интерполятора отказов.

BounceInterpolator bounceInterpolator = new BounceInterpolator();   
ObjectAnimator anim = ObjectAnimator.ofFloat(myViewGroup, "translationY", 0f, -200 );
anim.setInterpolator(bounceInterpolator);
anim.setDuration(1100).start();

Это вызовет плавную анимацию с эффектом отскока и действительно переместит представления, не похожие на анимацию, до Honeycomb. Из документов:

Предыдущие анимации изменили внешний вид целевых объектов ... но на самом деле они не изменили сами объекты.

1 голос
/ 27 августа 2018

Также вы можете изменить размер новой анимации Spring от Google.

Метод создания SpringAnimation:

fun getSpringAnimation(view: View, springAnimationType: FloatPropertyCompat<View>, finalPosition: Float): SpringAnimation {
    val animation = SpringAnimation(view, springAnimationType )
    // create a spring with desired parameters
    val spring = SpringForce()
    spring.finalPosition = finalPosition
    spring.stiffness = SpringForce.STIFFNESS_VERY_LOW // optional
    spring.dampingRatio = SpringForce.DAMPING_RATIO_NO_BOUNCY // optional
    // set your animation's spring
    animation.spring = spring
    return animation
}

Использование (изменение размера до 80% от исходного размера просмотра.)

 getSpringAnimation(view, SpringAnimation.SCALE_X, 0.8f).start()
 getSpringAnimation(view, SpringAnimation.SCALE_Y, 0.8f).start()
...