使用动画更改布局的权重

jbi*_*han 11 android android-animation android-layout

在我的主布局文件中,我有一个RelativeLayout,权重为1(基本上显示一个地图)在LinearLayout上方,权重为2,这样声明:

<LinearLayout
    android:id="@+id/GlobalLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/UpLayout"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1" >
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/DownLayout"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="2"
        android:orientation="vertical" >
    </LinearLayout>

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

DownLayout包含一个项目列表,当我点击一个项目时,我想将DownLayout的权重更改为4,因此上部布局(地图)仅占屏幕的1/5而不是1/3.

我设法通过更改LayoutParams来实现:

    LinearLayout linearLayout = (LinearLayout) mActivity.findViewById(R.id.DownLayout);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
    params.weight = 4.0f;
    linearLayout.setLayoutParams(params);
Run Code Online (Sandbox Code Playgroud)

它有效,但我不满意,变化太直接,没有过渡,而我希望它是顺利的.有没有办法使用动画?

我发现了一些使用ObjectAnimator来改变weightSum的例子,但它并不想要我想要的(如果我只改变这个属性,我在我的向下布局下面有一些空闲空间):

        float ws = mLinearLayout.getWeightSum();
        ObjectAnimator anim = ObjectAnimator.ofFloat(mLinearLayout, "weightSum", ws, 5.0f);
        anim.setDuration(3000);
        anim.addUpdateListener(this);
        anim.start();
Run Code Online (Sandbox Code Playgroud)

有没有办法使用ObjectAnimator(或其他东西)来做到这一点?

谢谢 !

Sta*_*kJP 25

我最近遇到了类似的问题并使用标准动画解决了它(我必须使用API​​ 10,因此无法使用ObjectAnimator).我在这里使用了答案的组合和轻微的改动,以考虑重量而不是高度.

我的自定义动画类看起来如下......

private class ExpandAnimation extends Animation {

    private final float mStartWeight;
    private final float mDeltaWeight;

    public ExpandAnimation(float startWeight, float endWeight) {
        mStartWeight = startWeight;
        mDeltaWeight = endWeight - startWeight;
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mContent.getLayoutParams();
        lp.weight = (mStartWeight + (mDeltaWeight * interpolatedTime));
        mContent.setLayoutParams(lp);
    }

    @Override
    public boolean willChangeBounds() {
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

它被这种方法称为......

public void toggle() {
    Animation a;
    if (mExpanded) {
        a = new ExpandAnimation(mExpandedWeight, mCollapsedWeight);
        mListener.onCollapse(mContent);
    } else {
        a = new ExpandAnimation(mCollapsedWeight, mExpandedWeight);
        mListener.onExpand(mContent);
    }

    a.setDuration(mAnimationDuration);
    mContent.startAnimation(a);
    mExpanded = !mExpanded;
}
Run Code Online (Sandbox Code Playgroud)

希望这会帮助你,如果你需要更多的细节或有任何问题让我知道.