Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

android - ObjectAnimator animate LinearLayout width

Ok, so i checked out http://android-developers.blogspot.com/2011/02/animation-in-honeycomb.html

He says you can animate the property of an object in a given time. And i tried moving around objects and it looks fine. I encountered a problem when i went changing the width of a LinearLayout. I got this:

10-26 14:51:27.190: E/PropertyValuesHolder(12681): Couldn't find setter/getter for       property width with value type float

Then i tried extending LinearLayout, with "myWidth"

public void setMyWidth(int myWidth) {
    LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
    params.weight = myWidth;
    setLayoutParams(params);
    requestLayout();
    this.myWidth = myWidth;
}

No luck. Then i tried changing LayoutParams.width, turns out width and height are the only public properties in java history, and ObjectAnimator needs getter and setter. No luck. I'm embarassed to say i tried extending LayoutParams too... with no luck ofc.

Anybody succeded doing such a thing? I used old android.view.animation and i got what i wanted, but i'm curious for the future.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In situations where there isn't a simple property getter/setter you should use ValueAnimator and perform the animation manually.

Assuming:

  • v is the view you're animating
  • END_WIDTH is the target width of the view in pixels.
  • DURATION is the desired length of the animation in milliseconds.

Your code should look something like this:

    ValueAnimator anim = ValueAnimator.ofInt(v.getMeasuredWidth(), END_WIDTH);
    anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {
            int val = (Integer) valueAnimator.getAnimatedValue();
            ViewGroup.LayoutParams layoutParams = v.getLayoutParams();
            layoutParams.width = val;
            v.setLayoutParams(layoutParams);
        }
    });
    anim.setDuration(DURATION);
    anim.start(); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...