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;
}
Related
I added Images view dynamically to my Linear layout,
I want to achieve
Here is sample code what I have done
MainActivity
package ksp.com.animationssample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private Button btn_expand;
private Button btn_collapse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_expand = (Button) findViewById(R.id.btn_expand);
btn_collapse = (Button) findViewById(R.id.btn_collapse);
LinearLayout.LayoutParams vp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
final LinearLayout layout = (LinearLayout) findViewById(R.id.imageLayout);
for (int i = 0; i < 3; i++) {
final ImageView image = new ImageView(MainActivity.this);
image.setLayoutParams(vp);
if (i == 0)
image.setImageDrawable(getResources().getDrawable(R.drawable.item_image1));
else image.setImageDrawable(getResources().getDrawable(R.drawable.item_image2));
if (i == 2)
image.setVisibility(View.VISIBLE);
else
image.setVisibility(View.GONE);
layout.addView(image);
}
btn_expand.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
expandOrCollapse(layout.getChildAt(2), true, layout.getChildAt(0).getHeight() + layout.getChildAt(1).getHeight());
expandOrCollapse(layout.getChildAt(1), true, layout.getChildAt(0).getHeight());
expandOrCollapse(layout.getChildAt(0), true, 0);
}
});
btn_collapse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
expandOrCollapse(layout.getChildAt(0), false, 0);
expandOrCollapse(layout.getChildAt(1), false, layout.getChildAt(0).getHeight());
expandOrCollapse(layout.getChildAt(2), false, layout.getChildAt(0).getHeight() + layout.getChildAt(1).getHeight());
}
});
}
public void expandOrCollapse(final View v, boolean is_expand, final int animheight) {
TranslateAnimation anim = null;
if (is_expand) {
anim = new TranslateAnimation(0.0f, 0.0f, -animheight, 0.0f);
v.setVisibility(View.VISIBLE);
Animation.AnimationListener expandedlistener = new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
};
anim.setAnimationListener(expandedlistener);
} else {
anim = new TranslateAnimation(0.0f, 0.0f, 0.0f, -animheight);
Animation.AnimationListener collapselistener = new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
v.setVisibility(View.GONE);
}
};
anim.setAnimationListener(collapselistener);
}
anim.setDuration(1500);
anim.setInterpolator(new AccelerateInterpolator(0.5f));
v.startAnimation(anim);
}
}
activity_mainn.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
android:background="#android:color/holo_blue_dark"
tools:context="ksp.com.animationssample.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:id="#+id/btn_expand"
android:text="Expand"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_collapse"
android:text="Collopse"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical">
<LinearLayout
android:layout_width="match_parent"
android:id="#+id/imageLayout"
android:gravity="center"
android:orientation="vertical"
android:layout_height="wrap_content">
</LinearLayout>
<!--android:animateLayoutChanges="true"-->
</ScrollView>
</RelativeLayout>
when I click expand button at the first time is not showing the animation from the second time it's working.
enable Visible the item after click on collapse button.
What to do next :
When I selected any View item it has to show select animation then collapse animation, after collapse it has to appear as top View like I mention in Image above. Currently I am hard code the count of the views and wrote static animations for each view with static heights of animations i.e (expandOrCollapse(view, height_of_view))
I search a while for this, but no luck.
I follow the Vie expand/collapse and smooth expand / collapse but they can't help me expand all views in Linear layout.
Can we do this List views are recycler view or something ?
for time saving I have added my sample to git hub you can try it Animation Sample Github
Suggest me, please.
I have made separate class for it. Check if it works for you:
public class DropDownAnim extends Animation {
private final int sourceHeight;
private final int targetHeight;
private final View view;
private final boolean down;
public DropDownAnim(View view, int sourceHeight, int targetHeight, boolean down) {
this.view = view;
this.sourceHeight = sourceHeight;
this.targetHeight = targetHeight;
this.down = down;
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
int newHeight;
if (down) {
newHeight = sourceHeight + (int) (targetHeight * interpolatedTime);
} else {
newHeight = sourceHeight + targetHeight - (int) (targetHeight * interpolatedTime);//(int) (targetHeight * (1 - interpolatedTime));
}
view.getLayoutParams().height = newHeight;
view.requestLayout();
view.setVisibility(down ? View.VISIBLE : View.GONE);
}
#Override
public void initialize(int width, int height, int parentWidth,
int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
}
#Override
public boolean willChangeBounds() {
return true;
}
}
While working with this. For expand
public void expand(final View v) {
final int sourceHeight = v.getLayoutParams().height;
final int targetHeight = getResources().getDimensionPixelSize(R.dimen.notification_height);//v.getMeasuredHeight();
DropDownAnim a = new DropDownAnim(v,targetHeight,true);
a.setDuration((int) (targetHeight / v.getContext().getResources().getDisplayMetrics().density));
a.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
// Your code on end of animation
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
v.setVisibility(View.INVISIBLE);
v.startAnimation(a);
}
For collapse:
public void collapse(final View v) {
final int sourceHeight = v.getLayoutParams().height;
final int targetHeight = v.getMeasuredHeight();
DropDownAnim a = new DropDownAnim(v, targetHeight, false);
a.setDuration((int) (targetHeight / v.getContext().getResources().getDisplayMetrics().density));
a.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
// Your code on end of animation
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
v.startAnimation(a);
}
Update:
sourceHeight added to prevent view blinking.
Try to not hide your target view (now you set visibility GONE for all views after collapsed animation end) and do this:
targetView.bringToFront();
targetView.invalidate();
targetView.getParent().requestLayout();
I am trying to achieve AlphaAnimation on an ImageView whenever user clicks on a RecyclerView item. I have the following code:
class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
TextView vh_idnumber, vh_task;
Information a;
View vh_colorTag;
FrameLayout checkboxLayout;
ImageView checkboxBackground;
Drawable checkBoxBackgroundDrawable;
private ScaleAnimation ZoomOut;
private ScaleAnimation ZoomIn;
#SuppressWarnings("deprecation")
public CustomViewHolder(View itemView)
{
super(itemView);
itemView.getId();
vh_idnumber = (TextView) itemView.findViewById(R.id.idnumber);
vh_task = (TextView) itemView.findViewById(R.id.task);
vh_colorTag = (View) itemView.findViewById(R.id.colortag);
checkboxLayout = (FrameLayout) itemView.findViewById(R.id.checkBoxLayout);
checkboxBackground = (ImageView) itemView.findViewById(R.id.checkBoxBackground);
checkBoxBackgroundDrawable= context.getResources().getDrawable(R.drawable.circle_shape);
checkboxBackground.setBackgroundDrawable(checkBoxBackgroundDrawable);
ZoomOut = new ScaleAnimation(1f, 0.3f, 1f, 0.3f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
checkboxBackground.setAnimation(ZoomOut);
ZoomOut.setDuration(100);
ZoomOut.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {}
#Override
public void onAnimationRepeat(Animation animation) {}
#Override
public void onAnimationEnd(Animation animation)
{
checkBoxBackgroundDrawable.setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP);
}
});
ZoomIn = new ScaleAnimation(0.3f, 1f, 0.3f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
checkboxBackground.setAnimation(ZoomIn);
ZoomIn.setDuration(100);
ZoomIn.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {}
#Override
public void onAnimationRepeat(Animation animation) {}
#Override
public void onAnimationEnd(Animation animation)
{
checkBoxBackgroundDrawable.setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_ATOP);
}
});
random = new Random();
int index = random.nextInt(colorCode.length);
if(!colorRibbon)
{
vh_colorTag.setVisibility(View.GONE);
}
else
{
vh_colorTag.setBackgroundColor(Color.parseColor(colorCode[index]));
}
itemView.setOnClickListener(this);
vh_task.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
a = MainActivity.data.get(getAdapterPosition());
if(a.availability.matches("available"))
{
vh_task.setPaintFlags(vh_task.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
vh_task.setTextColor(Color.RED);
a.availability="unavailable";
}
else if(a.availability.matches("unavailable"))
{
vh_task.setPaintFlags( vh_task.getPaintFlags() & (~ Paint.STRIKE_THRU_TEXT_FLAG));
vh_task.setTextColor(Color.parseColor("#212121"));
a.availability="available";
}
}
});
checkboxLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
changeStatus();
}
});
}
#Override
public void onClick(View v)
{
changeStatus();
}
protected void changeStatus()
{
a = MainActivity.data.get(getAdapterPosition());
if(a.status.matches("checked"))
{
/* This dont' work */
ZoomOut.start();
a.status="unchecked";
}
else if(a.status.matches("unchecked"))
{
/* Neither this */
ZoomIn.start();
a.status="checked";
}
}
}
The AlphaAnimation does not get triggered. But onClick event gets fired. Tested the onclick event using Log. If I replace Animation with anything else it works but the Animation wont work.
What you want is achievable using startAnimation instead of setAnimation
protected void changeStatus() {
a = MainActivity.data.get(getAdapterPosition());
if(a.status.matches("checked"))
{
checkboxBackground.startAnimation(ZoomOut);
a.status="unchecked";
}
else if(a.status.matches("unchecked")) {
checkboxBackground.startAnimation(ZoomIn);
a.status="checked";
}
}
setAnimation needs a start time for the animation to be set, and you will have to invalidate checkboxBackground's parent.
I did some animations with regards to my created button. However, after the animation, the button is at its new position, but the onclick function is at its old initial position. I did the onAnimationEnd and set the button to the new position but the Button and the invisible-like button with the onclick function moves together. Any help will be awesome
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//move
TranslateAnimation animation = new TranslateAnimation(0.0f, ((widthPixels / 2) - 100),
0.0f, 0.0f);
animation.setDuration(1000);
animation.setRepeatCount(0);
animation.setRepeatMode(0);
animation.setFillEnabled(true);
animation.setFillAfter(true);
//fade
// Play.setVisibility(View.VISIBLE);
Play.startAnimation(animationfadein);
Play.startAnimation(animation);
Play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(DreamTales.this, Stories.class);
startActivity(i);
}
});
}
}, DELAY);
animation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
Button Playghost = (Button) findViewById(R.id.PlayBtn);
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)Play.getLayoutParams();
lp.leftMargin = (widthPixels/100); // use topmargin for the y-property, left margin for the x-property of your view
Playghost.setLayoutParams(lp);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
I am trying to move a view on the screen to a random point by clicking it, then have it stay there and move again by click, however, the view only does the correct movement when starting at 0,0 coordinates, once changed, it is animating from random position to random position and finishing on a third random position.
here is my snippet, can some one please run this and see if it works properly? and if not, what am i missing?
public class MainActivity extends ActionBarActivity {
ImageView image;
Rect rect;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
final int height = displaymetrics.heightPixels;
final int width = displaymetrics.widthPixels;
image = (ImageView) findViewById(R.id.image);
findViewById(R.id.image).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int newLeft = ((int)Math.round(Math.random()*width))/2;
final int newTop = ((int)Math.round(Math.random()*height))/2;;
final int newRight = ((int)Math.round(Math.random()*width))/2;;
final int newBottom = ((int)Math.round(Math.random()*height))/2;;
rect = new Rect(newLeft, newTop, newRight, newBottom);
doSomeAnimation(rect);
}
});
}
public void doSomeAnimation(final Rect rect) {
final FrameLayout.LayoutParams imageParasms = (FrameLayout.LayoutParams) image.getLayoutParams();
TranslateAnimation animation = new TranslateAnimation(
imageParasms.leftMargin, rect.left, imageParasms.topMargin, rect.top);
animation.setDuration(1000);
animation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
FrameLayout.LayoutParams imageParasms = (FrameLayout.LayoutParams) image.getLayoutParams();
imageParasms.width = rect.width();
imageParasms.height = rect.height();
imageParasms.leftMargin = rect.left;
imageParasms.topMargin = rect.top;
image.setLayoutParams(imageParasms);
image.requestLayout();
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
image.startAnimation(animation);
}
It's better to use ValueAnimator, because TranslateAnimation uses matrix, and its very hard do deal with previous matrix values, I look source codes and understand that its better to use ValueAnimator, becauses have more control on how values are changing, I implemented it in different way, check this
public class MainActivity extends FragmentActivity {
ImageView image;
Random rnd = new Random();
int leftMargin;
int topMargin;
boolean xRunning;
boolean yRunning;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
final int height = displaymetrics.heightPixels;
final int width = displaymetrics.widthPixels;
image = (ImageView) findViewById(R.id.image);
findViewById(R.id.image).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int newLeft = rnd.nextInt(height);
int newTop = rnd.nextInt(width);
Point pt = new Point(newLeft, newTop);
doSomeAnimation(pt);
}
});
//This Handler is used for optimization, for setting a layout in one place, instead of calling
//it in every onAnimationUpdate method
image.post(new Runnable() {
#Override
public void run() {
if(xRunning && yRunning) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) image.getLayoutParams();
params.leftMargin = leftMargin;
params.topMargin = topMargin;
image.setLayoutParams(params);
}
image.postDelayed(this, 30);
}
});
}
public void doSomeAnimation(final Point pt) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) image.getLayoutParams();
ValueAnimator xAnim = ValueAnimator.ofFloat(pxFromDp(this, params.leftMargin), pt.x);
xAnim.setDuration(1000);
xAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
leftMargin = (int) dpFromPx(MainActivity.this, (float) animation.getAnimatedValue());
}
});
xAnim.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
xRunning = false;
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
xAnim.start();
xRunning = true;
ValueAnimator yAnim = ValueAnimator.ofFloat(pxFromDp(this, params.topMargin), pt.y);
yAnim.setDuration(1000);
yAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
topMargin = (int) dpFromPx(MainActivity.this, (float) animation.getAnimatedValue());
}
});
yAnim.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
yRunning = false;
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
yAnim.start();
yRunning = true;
}
public static float dpFromPx(final Context context, final float px) {
return px / context.getResources().getDisplayMetrics().density;
}
public static float pxFromDp(final Context context, final float dp) {
return dp * context.getResources().getDisplayMetrics().density;
}
}
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.