how to rotate button about its center in android - android

hi in my app i am trying to rotate button about its centre but it is not rotating based on its center instead it is moving from its position.below is my code please help me how to solve that issue.
public class example extends Activity {
float newAngle,oldAngle=0;
int flag=0;
int n=340;
RotateAnimation animation,animation1;
Button arrow;
Button left,right;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
arrow=(Button)findViewById(R.id.img);
left=(Button)findViewById(R.id.left);
right=(Button)findViewById(R.id.right);
final int width = arrow.getWidth();
final int height = arrow.getHeight();
left.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(flag>=0)
{
newAngle = oldAngle+ 30;
oldAngle=newAngle;
}
flag++;
Log.i("flag",""+flag);
animation = new RotateAnimation(oldAngle, newAngle);
animation.setFillAfter(true);
animation.setDuration(200);
arrow.startAnimation(animation);
}
});
}
}

Easier...
http://developer.android.com/reference/android/view/animation/RotateAnimation.html#RotateAnimation(float, float, int, float, int, float)
new RotateAnimation(_oldAngle, _newAngle, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

full example:
public class MyActivity extends Activity implements View.OnClickListener {
private ImageView _image;
private float _newAngle, _oldAngle;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
_image = (ImageView) findViewById(R.id.image);
}
public void onClick(View view) {
if (view.getId() == R.id.button) {
_newAngle = _oldAngle + 30;
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) _image.getLayoutParams();
int centerX = layoutParams.leftMargin + (_image.getWidth()/2);
int centerY = layoutParams.topMargin + (_image.getHeight()/2);
RotateAnimation animation = new RotateAnimation(_oldAngle, _newAngle, centerX, centerY);
animation.setDuration(0);
animation.setRepeatCount(0);
animation.setFillAfter(true);
_image.startAnimation(animation);
_oldAngle = _newAngle;
}
}
}

use
RotateAnimation(float fromDegrees, float toDegrees, float pivotX, float pivotY)
pivotX, pivotY - coordinates of button center. and it looks like your angles are the same

The simplest solution deserves to be mentioned:
button.setRotation( angle );
Put that in your onClick method. For example:
public void onClick( View v ) { v.setRotation( v.getRotation() + 30f ); }
See the View API.

Related

Why the location of view always resets after I use ObjectAnimator to View.TRANSLATION_X?

I created a simple app, just want when I click a button, the imageview will travel to another position.
Below is the code, but it seems that when I click the button, the imageview always begin with the original position, not the real position. Is there any problem with my code?
public class MainActivity extends Activity{
private ImageView iv;
private Button bt;
private AnimatorSet mAniSet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ddd);
iv = (ImageView) this.findViewById(R.id.imageView1);
bt = (Button) this.findViewById(R.id.button1);
mAniSet = new AnimatorSet();
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int pointOnScreen[] = new int[2];
iv.getLocationOnScreen(pointOnScreen);
ObjectAnimator AniTranslationX = ObjectAnimator.ofFloat(iv, View.TRANSLATION_X, pointOnScreen[0]+100);
mAniSet.playTogether(AniTranslationX);
mAniSet.setTarget(iv);
mAniSet.setDuration(200).start();
}
});
}
}
If you create a ObjectAnimator.ofFloat(Object, Property, values) and there is only one value, so the origin of the animation will be 0f.
You can find the source into the class android.animation.KeyFrameSet and the following method:
public static KeyframeSet ofFloat(float... values) {
boolean badValue = false;
int numKeyframes = values.length;
FloatKeyframe keyframes[] = new FloatKeyframe[Math.max(numKeyframes,2)];
if (numKeyframes == 1) {
keyframes[0] = (FloatKeyframe) Keyframe.ofFloat(0f);
keyframes[1] = (FloatKeyframe) Keyframe.ofFloat(1f, values[0]);
if (Float.isNaN(values[0])) {
badValue = true;
}
} else {
keyframes[0] = (FloatKeyframe) Keyframe.ofFloat(0f, values[0]);
for (int i = 1; i < numKeyframes; ++i) {
keyframes[i] =
(FloatKeyframe) Keyframe.ofFloat((float) i / (numKeyframes - 1), values[i]);
if (Float.isNaN(values[i])) {
badValue = true;
}
}
}
if (badValue) {
Log.w("Animator", "Bad value (NaN) in float animator");
}
return new FloatKeyframeSet(keyframes);
}
You can see, with only one value, the start of the animation is 0f (keyframes[0]).
If you put 2 values, your animation will start from the first value and stop at the second:
ObjectAnimator AniTranslationX = ObjectAnimator.ofFloat(iv, View.TRANSLATION_X, pointOnScreen[0], pointOnScreen[0] + 100);
With 3 or more values, the animation will reach all these values over the time of the animation.

ZigZag Animation of image in android

I am working an android app in which i have 10 balloons
i want to animate those balloons in zig zag style.
i am usning valueanimator
my code is
Display display = getWindowManager().getDefaultDisplay();
display.getRectSize(mDisplaySize);
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
mScale = metrics.density;
mRootLayout = (RelativeLayout) findViewById(R.id.main_layout);
new Timer().schedule(new ExeTimerTask(), 0, 2000);
}
public void startAnimation(final ImageView aniView) {
aniView.setPivotX(aniView.getWidth()/2);
aniView.setPivotY(aniView.getHeight()/2);
aniView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getBaseContext(), "Clicked", Toast.LENGTH_SHORT).show();
}
});
long delay = new Random().nextInt(Constants.MAX_DELAY);
final ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
animator.setDuration(Constants.ANIM_DURATION);
animator.setInterpolator(new AccelerateInterpolator());
animator.setStartDelay(delay);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
// int angle = 40 + (int)(Math.random() * 101);
//int angle = 40 + (int)(Math.random() * 101);
int movex = new Random().nextInt(mDisplaySize.right);
#Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = ((Float) (animation.getAnimatedValue())).floatValue();
// aniView.setRotation(angle*value);
aniView.setTranslationX((movex-40)*value);
aniView.setTranslationY((mDisplaySize.bottom + (150*mScale))*value);
}
});
animator.start();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int viewId = new Random().nextInt(LEAVES.length);
Drawable d = getResources().getDrawable(LEAVES[viewId]);
LayoutInflater inflate = LayoutInflater.from(FallAnimationActivity.this);
ImageView imageView = (ImageView) inflate.inflate(R.layout.ani_image_view, null);
imageView.setImageDrawable(d);
mRootLayout.addView(imageView);
mAllImageViews.add(imageView);
LayoutParams animationLayout = (LayoutParams) imageView.getLayoutParams();
animationLayout.setMargins(0, (int)(-150*mScale), 0, 0);
animationLayout.width = (int) (60*mScale);
animationLayout.height = (int) (60*mScale);
startAnimation(imageView);
}
};
private class ExeTimerTask extends TimerTask {
#Override
public void run() {
// we don't really use the message 'what' but we have to specify something.
mHandler.sendEmptyMessage(Constants.EMPTY_MESSAGE_WHAT);
}
}
but it's motion is not zigzag how to make animation zigzag any idea thanks in advance
try this:
class ZigZagAnimation extends Animation {
private PathMeasure pm;
float[] pos = new float[2];
public ZigZagAnimation() {
Path p = new Path();
p.moveTo(0f, 0f);
p.lineTo(12f, 5f);
p.lineTo(8f, 14f);
p.lineTo(25f, 17f);
p.lineTo(13f, 31f);
pm = new PathMeasure(p, false);
setDuration(4000);
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
float distance = pm.getLength() * interpolatedTime;
pm.getPosTan(distance, pos, null);
t.getMatrix().postTranslate(pos[0], pos[1]);
}
}
I did it with two different animations, one to slide on X/Y axis and one for moving in the remain axis:
shake.xml (On Y axis):
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:duration="40"
android:fromYDelta="0%"
android:toYDelta="-8%"
android:repeatCount="5"
android:repeatMode="reverse"
/>
</set>
in activity ( + X axis movement):
float ctr = 0f;
imageView.startAnimation(AnimationUtils.loadAnimation(this, R.anim.shake));
while (ctr <= X_YOU_WANT_TO_REACH) {
imageView.animate().x(ctr).setDuration(500).start();
ctr++;
}

Animate view sliding out of another view, pushing views below out of the way

I have a list of buttons. When I press a button, a View should slide in a downwards motion out of the button, like this:
Start:
Halfway:
End:
How would I go about this? The View that should slide out is bigger than the button, so first hiding the View behind the button and then sliding it downwards causes the View to be visible above the button. That should not happen.
Any ideas or examples on how to approach this?
I believe the simplest approach is to extend Animation class and override applyTransformation() to change the view's height as follows:
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.LinearLayout;
public class MyCustomAnimation extends Animation {
public final static int COLLAPSE = 1;
public final static int EXPAND = 0;
private View mView;
private int mEndHeight;
private int mType;
private LinearLayout.LayoutParams mLayoutParams;
public MyCustomAnimation(View view, int duration, int type) {
setDuration(duration);
mView = view;
mEndHeight = mView.getHeight();
mLayoutParams = ((LinearLayout.LayoutParams) view.getLayoutParams());
mType = type;
if(mType == EXPAND) {
mLayoutParams.height = 0;
} else {
mLayoutParams.height = LayoutParams.WRAP_CONTENT;
}
view.setVisibility(View.VISIBLE);
}
public int getHeight(){
return mView.getHeight();
}
public void setHeight(int height){
mEndHeight = height;
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
if (interpolatedTime < 1.0f) {
if(mType == EXPAND) {
mLayoutParams.height = (int)(mEndHeight * interpolatedTime);
} else {
mLayoutParams.height = (int) (mEndHeight * (1 - interpolatedTime));
}
mView.requestLayout();
} else {
if(mType == EXPAND) {
mLayoutParams.height = LayoutParams.WRAP_CONTENT;
mView.requestLayout();
}else{
mView.setVisibility(View.GONE);
}
}
}
}
To use it, set your onclick() as follows:
int height;
#Override
public void onClick(View v) {
if(view2.getVisibility() == View.VISIBLE){
MyCustomAnimation a = new MyCustomAnimation(view2, 1000, MyCustomAnimation.COLLAPSE);
height = a.getHeight();
view2.startAnimation(a);
}else{
MyCustomAnimation a = new MyCustomAnimation(view2, 1000, MyCustomAnimation.EXPAND);
a.setHeight(height);
view2.startAnimation(a);
}
}
Regards.
Use something like:
Animation a = new ScaleAnimation(1, 1, 0, 1, Animation.RELATIVE_TO_SELF, (float) 0.5, Animation.RELATIVE_TO_SELF, (float) 0);
a.setFillAfter(true);
view.setAnimation(a);
a.setDuration(1000);
view.startAnimation(a);
Here is simple example of hand-made animation, that provide what you want. It works in test app, but I'm not sure that there is no bugs:
public class MainActivity extends Activity implements OnClickListener {
private Timer timer;
private TimerTask animationTask;
private View view1;
private View view2;
boolean animating;
boolean increasing = true;
int initHeight = -1;
private LayoutParams params;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer = new Timer();
view1 = findViewById(R.id.view1);// clickable view
view1.setOnClickListener(this);
view2 = findViewById(R.id.view2);// animated view
params = view2.getLayoutParams();
}
#Override
protected void onDestroy() {
super.onDestroy();
timer.cancel();
}
#Override
public void onClick(View v) {
Toast.makeText(this, "start animating...", Toast.LENGTH_SHORT).show();
animationTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (animationFinished()) {
animating = false;
cancel();//canceling animating task
return;
}
params.height += increasing ? 1 : -1;
view2.setLayoutParams(params);
}
});
}
private boolean animationFinished() {
int viewHeight = view2.getHeight();
if (increasing && viewHeight >= initHeight) {
return true;
}
if (!increasing && viewHeight <= 0) {
return true;
}
return false;
}
};
//if we already animating - we just change direction of animation
increasing = !increasing;
if (!animating) {
animating = true;
int height = view2.getHeight();
params.height = height;
view2.setLayoutParams(params);//change param "height" from "wrap_conent" to real height
if (initHeight < 0) {//height of view - we setup it only once
initHeight = height;
}
timer.schedule(animationTask, 0, 10);//changing repeat time here will fasten or slow down animation
}
}
}
Maybe you can set the height to 0 and gradually increase the height. But then you will have the problem that you have to be sure your text is aligned at the bottom of the view. And also to know what the maximal height of the view should be.
use a sliding list adapter so much easier than messing around with animations
https://github.com/tjerkw/Android-SlideExpandableListView
Simply pass android:animateLayoutChanges to LinearLayout that holds all the views, you will achieve your desired result.
I would do it like that. First the layout for the whole collapsible panel component: (pseudo xml)
RelativeLayout (id=panel, clip)
LinearLayout (id=content, alignParentBottom=true)
LinearLayout (id=handle, above=content)
This should ensure that the content is always below the handle.
Then when you need to collapse:
Animate the top margin of content from 0 to -content.height
Animate the height of the panel from current to current-content.height

Top to bottom - translate animation

Need to make next animation (on android 2.2 and above):
1.Moving button from top to bottom (after clicking on him),
2.Moving back from bottom to top (After clicking on him again).
First animation works fine, but the second not, the btn "jumps" from bottom to top and not animate.
Code:
public class MainActivity extends Activity {
static RelativeLayout relativeLayout;
static Button btn;
static Boolean isUp = true;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button1);
relativeLayout = (RelativeLayout) findViewById(R.id.relative_layout);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isUp){
isUp = false;
v.startAnimation(MainActivity.getVerticalSlideAnimation(0,relativeLayout.getBottom() - v.getHeight(),500,0));
}else{
isUp = true;
v.startAnimation(MainActivity.getVerticalSlideAnimation(relativeLayout.getBottom() - v.getHeight(),0,500,0));
}
}
});
}
public static Animation getVerticalSlideAnimation(int fromYPosition, final int toYPosition, int duration, int startOffset)
{
TranslateAnimation translateAnimation = new TranslateAnimation(1, 0.0F, 1, 0.0F, 0, fromYPosition, 0, toYPosition);
translateAnimation.setDuration(duration);
translateAnimation.setInterpolator(new AccelerateInterpolator());
translateAnimation.setStartOffset(startOffset);
//Stop animation after finishing.
//translateAnimation.setFillAfter(true);
translateAnimation.setAnimationListener(new AnimationListener()
{
public void onAnimationStart(Animation animation) { }
public void onAnimationRepeat(Animation animation) { }
public void onAnimationEnd(Animation animation) {
btn.setY(toYPosition);
}
});
return translateAnimation;
}
}
Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relative_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
Ok, I solved it.
There are few issuses you should know about animation:
The animation paremeters are not simple "From (fixed position)" --> "To (fix position)" as you should think. There are more like "From (current position/0)" --> "How much steps to do and on which direction (pluse for positive/ minus for negative)"
The Animation doesn't change the real position of the view on the screen, Therefore if you want to stop the animation at the end position, you should use:
animation.setFillAfter(true);
If you do want to change the REAL position of the view you should update the view parameters on "onAnimationEnd" (like below code), or calculate position and set Y/X position manually (again on "onAnimationEnd"), like:
animatedView.setY(stopPosition);
The Code:
public class AnimationActivity extends Activity {
private boolean isUp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById(R.id.button1))
.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
final float direction = (isUp) ? -1 : 1;
final float yDelta = getScreenHeight() - (2 * v.getHeight());
final int layoutTopOrBottomRule = (isUp) ? RelativeLayout.ALIGN_PARENT_TOP : RelativeLayout.ALIGN_PARENT_BOTTOM;
final Animation animation = new TranslateAnimation(0,0,0, yDelta * direction);
animation.setDuration(500);
animation.setAnimationListener(new AnimationListener() {
public void onAnimationStart(Animation animation) {
}
public void onAnimationRepeat(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
// fix flicking
// Source : http://stackoverflow.com/questions/9387711/android-animation-flicker
TranslateAnimation anim = new TranslateAnimation(0.0f, 0.0f, 0.0f, 0.0f);
anim.setDuration(1);
v.startAnimation(anim);
//set new params
LayoutParams params = new LayoutParams(v.getLayoutParams());
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
params.addRule(layoutTopOrBottomRule);
v.setLayoutParams(params);
}
});
v.startAnimation(animation);
//reverse direction
isUp = !isUp;
}
});
}
private float getScreenHeight() {
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
return (float) displaymetrics.heightPixels;
}
}
public class AnimationActivity extends Activity {
private boolean isUp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById(R.id.button1))
.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
final float direction = (isUp) ? -1 : 1;
final float yDelta = getScreenHeight() - (2 * v.getHeight());
final int layoutTopOrBottomRule = (isUp) ? RelativeLayout.ALIGN_PARENT_TOP : RelativeLayout.ALIGN_PARENT_BOTTOM;
final Animation animation = new TranslateAnimation(0,0,0, yDelta * direction);
animation.setDuration(500);
animation.setAnimationListener(new AnimationListener() {
public void onAnimationStart(Animation animation) {
}
public void onAnimationRepeat(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
// fix flicking
// Source : http://stackoverflow.com/questions/9387711/android-animation-flicker
TranslateAnimation anim = new TranslateAnimation(0.0f, 0.0f, 0.0f, 0.0f);
anim.setDuration(1);
v.startAnimation(anim);
//set new params
LayoutParams params = new LayoutParams(v.getLayoutParams());
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
params.addRule(layoutTopOrBottomRule);
v.setLayoutParams(params);
}
});
v.startAnimation(animation);
//reverse direction
isUp = !isUp;
}
});
}
private float getScreenHeight() {
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
return (float) displaymetrics.heightPixels;
}

How to expand a layout height with animation?

I couldn't find a good example for how to do this.
I have a RelativeLayout set with x height.
I want to add a button which expands the height to x+y height.
can someone refer me to a good example on how to do it programmatically?
You marked the solution that was closest. This is the exact solution. I had the same problem. Hopefully this answer will help others.
InstantiateResizeAnimation
ResizeAnimation resizeAnimation = new ResizeAnimation(
view,
targetHeight,
startHeight
);
resizeAnimation.setDuration(duration);
view.startAnimation(resizeAnimation);
ResizeAnimation class should look like this
public class ResizeAnimation extends Animation {
final int targetHeight;
View view;
int startHeight;
public ResizeAnimation(View view, int targetHeight, int startHeight) {
this.view = view;
this.targetHeight = targetHeight;
this.startHeight = startHeight;
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
int newHeight = (int) (startHeight + targetHeight * interpolatedTime);
//to support decent animation, change new heigt as Nico S. recommended in comments
//int newHeight = (int) (startHeight+(targetHeight - startHeight) * interpolatedTime);
view.getLayoutParams().height = newHeight;
view.requestLayout();
}
#Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
}
#Override
public boolean willChangeBounds() {
return true;
}
}
You need a scale animation here is the official documentation
this is in code
private void animate() {
ImageView imageView = (ImageView) findViewById(R.id.ImageView01);
ScaleAnimation scale = new ScaleAnimation((float)1.0, (float)1.5, (float)1.0, (float)1.5);
scale.setFillAfter(true);
scale.setDuration(500);
imageView.startAnimation(scale);
}
Please check below new edited answer as below. But here you need to know the exact new height.
public class LayoutAnimationActivity extends Activity {
RelativeLayout ril1;
Button btn;
int initialHeight;
int actualHeight;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
ril1 = (RelativeLayout) findViewById(R.id.relativeLayout1);
btn = new Button(this);
btn.setWidth(100);
btn.setHeight(200);
btn.setText("Button");
actualHeight = 210;
Ani a = new Ani();
a.setDuration(2000);
ril1.startAnimation(a);
}
class Ani extends Animation {
public Ani() {}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
int newHeight;
newHeight = (int) (initialHeight * interpolatedTime);
ril1.removeAllViews();
btn.setWidth(100);
btn.setHeight(300);
btn.setText("as");
ril1.addView(btn);
ril1.getLayoutParams().height = newHeight;
ril1.requestLayout();
}
#Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
initialHeight = actualHeight;
}
#Override
public boolean willChangeBounds() {
return true;
}
};
}
Two simple ways to do this without an Animation class:
1) Set android:animateLayoutChanges="true" in you xml layout file
2) Use a ViewProperty animator
layout.setPivot(0);
layout.animate().scaleY(scaleFactor).setDuration(500);
The pivot tells the view where to scale from, default is in the middle, which in my experience is almost never what you want. The duration is optional (default = 1000).
final Button button1 = (Button) view.findViewById(R.id.button);
final CollapseAnimator animator = new CollapseAnimator(topLayout);
final ViewTreeObserver.OnGlobalLayoutListener listener = new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int mHeight = button1.getMeasuredHeight();
KLog.i("onGlobalLayout() mHeight:" + mHeight);
animator.setValues(mHeight*2, mHeight);
}
};
button1.getViewTreeObserver().addOnGlobalLayoutListener(listener);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
view.post(new Runnable() {
#Override
public void run() {
button1.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
animator.collapse();
}
});
}
});
and class
public class CollapseAnimator {
private View view;
private boolean collapse=true;
private int duation=300;
private int destHeight=300;
private ValueAnimator animator;
private int originHeight=0;
private int from=0;
private int to=0;
public CollapseAnimator(View view ) {
this.view = view;
}
public void setValues(int destHeight,int originHeight){
this.destHeight = destHeight;
this.originHeight=originHeight;
from=originHeight;
to=originHeight;
}
public void collapse(){
from=to;
if(collapse){
to=destHeight;
collapse=false;
}else{
to=originHeight;
collapse=true;
}
KLog.i("from:" + from+",to:"+to);
animator = ValueAnimator.ofInt(from, to);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
int val = (Integer) valueAnimator.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
layoutParams.height = val;
view.setLayoutParams(layoutParams);
}
});
animator.setDuration(duation);
animator.start();
}
}

Categories

Resources