I am trying to animate a layout to hide itself (to later animate other layout to take its place also by animation). Must be SDK 8 (android 2.2) compatible.
What I have works great IF the movingLayout's parent (parent_of_moving_layout in my xml) is twice the movingLayout's height, but I want the parent to be the same height so the movingLayout hides itself below so that I can animate another movingLayout2 later to take its place.
I have been working on it for some long hours and I can't find a solution, hoping someone has an idea (tried setFillAfter and setFillEnabled).
Here is my code and xml to reproduce the result:
activity_my.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MyActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MOVE IT"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="#+id/parent_of_moving_layout">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="50dp"
android:background="#ff93c049"
android:id="#+id/movinglayout"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test Button"
android:id="#+id/testbutton"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</RelativeLayout>
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="80dp"
android:layout_below="#+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="83dp"></FrameLayout>
</RelativeLayout>
MyActivity.java
package coersum.com.testanimation;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.RelativeLayout;
public class MyActivity extends ActionBarActivity {
//Button clicked to make movingLayout move (mButton) and button to make sure the objects moved and not only their displays (testButton)
Button mButton, testButton;
//layout to move and its LayoutParams (relative seems to be the only one that worked on my tests)
RelativeLayout movingLayout;
RelativeLayout.LayoutParams params;
//used to direction of movement for testing
String direction = "down";
//just a counter to see the Log.d changes more clearly
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(mButtonClickListener);
testButton = (Button) findViewById(R.id.testbutton);
testButton.setOnClickListener(testButtonClickListener);
movingLayout = (RelativeLayout) findViewById(R.id.movinglayout);
params = (RelativeLayout.LayoutParams) movingLayout.getLayoutParams();
}
private View.OnClickListener mButtonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
TranslateAnimation animation;
if (direction.equals("down")) {
animation = new TranslateAnimation(0, 0, 0, 50);
} else {
animation = new TranslateAnimation(0, 0, 0, -50);
}
animation.setFillAfter(true);
animation.setFillEnabled(true);
animation.setDuration(500);
animation.setAnimationListener(mAnimationListener);
movingLayout.startAnimation(animation);
}
};
private View.OnClickListener testButtonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
Log.d("Status", "Clicked on Test Button "+count+" "+direction);
}
};
private Animation.AnimationListener mAnimationListener = new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
movingLayout.clearAnimation();
if (direction.equals("down")) {
direction = "up";
params.topMargin = params.topMargin + 50;
} else {
direction = "down";
params.topMargin = params.topMargin - 50;
}
movingLayout.setLayoutParams(params);
}
};
}
After a few more hours of trials, I found an easy and clean solution (it was really just sooo simple, animate down then set View.GONE and to bring it back, set View.VISIBLE before animating up)! Added a scale for DP and finally made the difference between margin and translation.
Here is an updated java file:
package coersum.com.testanimation;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.RelativeLayout;
public class MyActivity extends Activity {
//Button clicked to make movingLayout move (mButton) and button to make sure the objects moved and not only their displays (testButton)
Button mButton, testButton;
//layout to move and its LayoutParams (relative seems to be the only one that worked on my tests)
RelativeLayout movingLayout;
RelativeLayout.LayoutParams params;
//used to direction of movement for testing
String direction = "down";
//just a counter to see the Log.d changes more clearly
int count = 0;
int convertedSize;
float scale;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
scale = getResources().getDisplayMetrics().density;
convertedSize = (int) (50 * scale + 0.5f); // my layout is 50dp in height set it to (minus)-your_size to go up instead of down
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(mButtonClickListener);
testButton = (Button) findViewById(R.id.testbutton);
testButton.setOnClickListener(testButtonClickListener);
movingLayout = (RelativeLayout) findViewById(R.id.movinglayout);
params = (RelativeLayout.LayoutParams) movingLayout.getLayoutParams();
}
private View.OnClickListener mButtonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
TranslateAnimation animation;
if (direction.equals("down")) {
animation = new TranslateAnimation(0, 0, 0, convertedSize);
} else {
movingLayout.setVisibility(View.VISIBLE); // show the layout before to animate it
animation = new TranslateAnimation(0, 0, convertedSize, 0);
}
animation.setDuration(500);
animation.setAnimationListener(mAnimationListener);
movingLayout.startAnimation(animation);
}
};
private View.OnClickListener testButtonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
count++; // just for debugging (to make sure the button was gone and not just its display)
Log.d("Status", "Clicked on Test Button " + count + " Dir: " + direction + " Size: " + convertedSize);
}
};
private Animation.AnimationListener mAnimationListener = new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
if (direction.equals("down")) {
movingLayout.setVisibility(View.GONE); // once it translated down, remove it so I'll be free to set other layout to visible to use etc
direction = "up";
} else {
direction = "down";
}
movingLayout.setLayoutParams(params);
movingLayout.clearAnimation();
}
};
public void testClick(View view) {
}
}
The setting of margin is good if you want to just move the layout inside the screen (and actually move the objects and not just their "display" which is what animations do below Honeycomb sdk, but that wasn't my case so this, so far seems to work perfectly.
Related
I got swipe up and swipe down for a layout by using setOnTouchListener (For understanding see below images)
Images
But i want to swipe up and swipe down the layout when clicking on the button not when OnTouchListener. For this i tried almost all examples in the online but i didn't get any solution according to my requirement. So, please help me to make OnTouchListener event when clicking on the button
My Code
Activity
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.RelativeLayout;
public class SwipeUpActivity extends Activity {
RelativeLayout rlSwipeHolder, rlSwipe1, rlSwipe2;
private float startY;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe_up);
rlSwipeHolder = (RelativeLayout) findViewById(R.id.rl_swipe_up_holder);
rlSwipe1 = (RelativeLayout) findViewById(R.id.rl_swipe_up_1);
rlSwipe2 = (RelativeLayout) findViewById(R.id.rl_swipe_up_2);
rlSwipe2.setVisibility(View.GONE);
rlSwipeHolder.setOnTouchListener(new OnTouchListener() {
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startY = event.getY();
break;
case MotionEvent.ACTION_UP: {
float endY = event.getY();
if (endY < startY) {
System.out.println("Move UP");
rlSwipeHolder.setVisibility(View.VISIBLE);
rlSwipe1.setVisibility(View.VISIBLE);
rlSwipe2.setVisibility(View.VISIBLE);
} else {
rlSwipeHolder.setVisibility(View.VISIBLE);
rlSwipe1.setVisibility(View.VISIBLE);
rlSwipe2.setVisibility(View.GONE);
}
}
}
return true;
}
});
}
}
Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
tools:context="com.app.swipeup.SwipeUpActivity" >
<RelativeLayout
android:id="#+id/rl_swipe_up_holder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#0000FF"
android:padding="5dp" >
<RelativeLayout
android:id="#+id/rl_swipe_up_1"
android:layout_width="match_parent"
android:layout_height="30dp"
android:background="#585858" >
</RelativeLayout>
<RelativeLayout
android:id="#+id/rl_swipe_up_2"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_below="#+id/rl_swipe_up_1"
android:background="#FE2E2E" >
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
Edit
Like this video i have to open the layout and close the layout (or swipe up the layout and swipe down the layout) when clicking the button
Create object of your onTouchListenr.
OnTouchListener ot = new OnTouchListener(){-------- YOUR CODE ---}
on enable button click
rlSwipeHolder.setOnTouchListener(ot);
on disable button clik
rlSwipeHolder.setOnTouchListener(null);
This is not the exact solution for this, but i'm posting here, because it may help others.
Answer
I saw lot of solutions for setOnTouchListener after setOnClickListener but i didn't get. So, i followed the animation for layout up and down as discussed in this link
and i did minute changes to the code as
Activity
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.RelativeLayout;
public class SwipeUpActivity extends Activity {
RelativeLayout mRelativeLayout;
RelativeLayout mRelativeLayoutHeader;
ValueAnimator mAnimator;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe_up);
mRelativeLayout = (RelativeLayout) findViewById(R.id.expandable);
// mLinearLayout.setVisibility(View.GONE);
mRelativeLayoutHeader = (RelativeLayout) findViewById(R.id.header);
// Add onPreDrawListener
mRelativeLayout.getViewTreeObserver().addOnPreDrawListener(
new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
mRelativeLayout.getViewTreeObserver().removeOnPreDrawListener(this);
mRelativeLayout.setVisibility(View.GONE);
final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
mRelativeLayout.measure(widthSpec, heightSpec);
mAnimator = slideAnimator(0, mRelativeLayout.getMeasuredHeight());
return true;
}
});
mRelativeLayoutHeader.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mRelativeLayout.getVisibility() == View.GONE) {
expand();
} else {
collapse();
}
}
});
}
private void expand() {
// set Visible
mRelativeLayout.setVisibility(View.VISIBLE);
mAnimator.start();
}
private void collapse() {
int finalHeight = mRelativeLayout.getHeight();
ValueAnimator mAnimator = slideAnimator(finalHeight, 0);
mAnimator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationEnd(Animator animator) {
// Height=0, but it set visibility to GONE
mRelativeLayout.setVisibility(View.GONE);
}
#Override
public void onAnimationStart(Animator animator) {
}
#Override
public void onAnimationCancel(Animator animator) {
}
#Override
public void onAnimationRepeat(Animator animator) {
}
});
mAnimator.start();
}
private ValueAnimator slideAnimator(int start, int end) {
ValueAnimator animator = ValueAnimator.ofInt(start, end);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
// Update Height
int value = (Integer) valueAnimator.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = mRelativeLayout.getLayoutParams();
layoutParams.height = value;
mRelativeLayout.setLayoutParams(layoutParams);
}
});
return animator;
}
}
Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<RelativeLayout
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="64dp"
android:background="#FCF">
</RelativeLayout>
<RelativeLayout
android:id="#+id/expandable"
android:layout_width="match_parent"
android:layout_height="64dp"
android:layout_below="#+id/header"
android:background="#FFF">
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
I try to make some tests with UX and animation. I want at a click on a button to expand it until the button has the size of his parent layout. Here is my very simple interface :
I succeed to create my own animation, it's just a simple class that takes the begin X, the end X, the begin Y and the end Y. Here is the class :
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;
public class ExpandAnimation extends Animation {
protected final View view;
protected float perValueH, perValueW;
protected final int originalHeight, originalWidth;
public ExpandAnimation(View view, int fromHeight, int toHeight, int fromWidth, int toWidth) {
this.view = view;
this.originalHeight = fromHeight;
this.originalWidth = fromWidth;
this.perValueH = (toHeight - fromHeight);
this.perValueW = (toWidth - fromWidth);
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
view.getLayoutParams().height = (int) (originalHeight + perValueH * interpolatedTime);
view.getLayoutParams().width = (int) (originalWidth + (perValueW * interpolatedTime)*2);
view.requestLayout();
}
#Override
public boolean willChangeBounds() {
return true;
}
}
The animation is pretty good and works as expected :
Here is my main loop :
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button left;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
left = (Button) findViewById(R.id.left);
left.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewGroup parent = (ViewGroup) view.getParent();
ExpandAnimation animation = new ExpandAnimation(view, view.getBottom(), parent.getTop(), view.getLeft(), parent.getRight());
animation.setDuration(3000);
animation.setFillAfter(true);
view.startAnimation(animation);
}
});
}
}
But I have 3 major issues :
First, the text is gone and I don't know why...
On the other hand, I want that my animation come over others views, but when I tried it wasn't working how can I achieve this ?
And last but not least, at the end of my animation, the button is gone and there is just an ugly artefact... How can I avoid that ?
Edit : my layout :
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="MainActivity">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="150dp"
android:weightSum="3"
android:padding="15dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:gravity="bottom">
<Button
android:id="#+id/left"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Retenter"
android:textSize="15dp"
android:textColor="#FFF"
android:background="#FF33CC44" />
</LinearLayout>
</RelativeLayout>
Edit2 : The artefact which appears at the end of the animation is due to the method setLayerType(View.LAYER_TYPE_SOFTWARE, null).
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
view.getLayoutParams().height = (int) (originalHeight + perValueH * interpolatedTime);
view.getLayoutParams().width = (int) (originalWidth + (perValueW * interpolatedTime));
view.requestLayout();
}
remove *2 will result below.
I am working on morphing a floating action button (FAB) to a toolbar and things work smoothly and perfectly with the following code:
layout file:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="sg.com.saurabh.designlibraryexpirements.ToolbarMorphActivity">
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|right"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:layout_marginRight="#dimen/activity_vertical_margin"
android:layout_marginBottom="#dimen/activity_vertical_margin"
android:src="#drawable/ic_add" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
style="#style/ToolBarTheme"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="top"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:layout_marginBottom="#dimen/activity_vertical_margin"
android:visibility="invisible"
tools:visibility="visible" />
</FrameLayout>
activity:
package sg.com.saurabh.designlibraryexpirements;
import android.animation.Animator;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.animation.FastOutLinearInInterpolator;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AnticipateOvershootInterpolator;
public class ToolbarMorphActivity extends AppCompatActivity {
Toolbar toolbar;
FloatingActionButton fab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toolbar_morph);
toolbar = (Toolbar) findViewById(R.id.toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(mFabClickListener);
}
private View.OnClickListener mFabClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
fab.animate()
.rotationBy(45)
.setInterpolator(new AnticipateOvershootInterpolator())
.setDuration(250)
.start();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
fab.setVisibility(View.GONE);
}
},50);
revealToolbar();
}
};
private void revealToolbar() {
toolbar.setVisibility(View.VISIBLE);
int x = (int)fab.getX() + fab.getWidth()/2;
int y = (int)fab.getY() + fab.getHeight()/2;
Animator animator = ViewAnimationUtils.createCircularReveal(toolbar, x, y, 0, toolbar.getWidth())
.setDuration(400);
animator.setInterpolator(new FastOutLinearInInterpolator());
animator.start();
}
private void dismissToolbar() {
int x = (int)fab.getX() + fab.getWidth()/2;
int y = (int)fab.getY() + fab.getHeight()/2;
Animator animator = ViewAnimationUtils.createCircularReveal(toolbar, x, y, toolbar.getWidth(), 0)
.setDuration(400);
animator.setInterpolator(new LinearOutSlowInInterpolator());
animator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
toolbar.setVisibility(View.INVISIBLE);
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
animator.start();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
fab.setVisibility(View.VISIBLE);
fab.animate()
.rotationBy(-45)
.setInterpolator(new AccelerateInterpolator())
.setDuration(100)
.start();
}
},200);
}
#Override
public void onBackPressed() {
if(toolbar.getVisibility() == View.VISIBLE) {
dismissToolbar();
}
else
super.onBackPressed();
}
}
The circular reveal works as expected for the above layout. However thing break up when I change the layout_gravity of the fab and toolbar to bottom instead of top. The rotate animation works and then the toolbar just appears without the circular reveal animation. I am completely stumped by how that breaks the circular reveal animation.
The fix for you would be to replace:
private void revealToolbar() {
....
int x = (int)fab.getX() + fab.getWidth()/2;
int y = (int)fab.getY() + fab.getHeight()/2;
....
}
by
private void revealToolbar() {
...
int x = (int)fab.getX() + fab.getWidth()/2;
int y = fab.getHeight()/2;
...
}
The reason is that createCircularReveal is taking parameters centerY and centerX as coordinates of the center of the animating circle, relative to view (i.e. Toolbar, in our case).
See method ViewAnimationUtils.createCircularReveal definition:
........
* #param view The View will be clipped to the animating circle.
* #param centerX The x coordinate of the center of the animating circle, relative to
* <code>view</code>.
* #param centerY The y coordinate of the center of the animating circle, relative to
* <code>view</code>.
* #param startRadius The starting radius of the animating circle.
* #param endRadius The ending radius of the animating circle.
*/
I am trying to rotate an imagebutton to 360 by clicking itself but it doesn't work
I am using xml file like this..
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="72dp"
android:layout_height="72dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="83dp"
android:layout_marginTop="103dp"
android:clickable="true"
android:src="#drawable/cute" />
</RelativeLayout>
and java code like this...
package com.example.testapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.RotateAnimation;
import android.widget.ImageButton;
public class MainActivity extends Activity implements OnClickListener {
ImageButton img;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageButton) findViewById(R.id.imageView1);
}
public void onClick(View v) {
// TODO Auto-generated method stub
RotateAnimation ra =new RotateAnimation(0, 360);
ra.setFillAfter(true);
ra.setDuration(0);
img.startAnimation(ra);
}
}
my aim of application is using 9 img btn develop and puzzle find game....
Your code works just fine. the problem is : you set duration to 0. You can't see it happen because if you rotate 360 degrees its ending position and starting position will be identical . so set the duration 1000(a second) or more to see the animation actualy happening.
just try:
ra.setDuration(1000);
And you also did not set the onClick listener of img.
just try:
img .setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//animation here
}
});
This was the code which I used to rotate in one small app.
public class MainScreen extends Activity{
ImageView ivDH = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.screen);
ivDH = (ImageView) findViewById(R.id.dollhouse);
ivDH.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
startAnimation(ivDH);
return false;
}
});
}
public void startAnimation(ImageView ivDH)
{
System.out.println("Inside startAnimation()");
Animation scaleAnim = new ScaleAnimation(0, 2, 0, 2);
scaleAnim.setDuration(5000);
scaleAnim.setRepeatCount(1);
scaleAnim.setInterpolator(new AccelerateInterpolator());
scaleAnim.setRepeatMode(Animation.REVERSE);
Animation rotateAnim = new RotateAnimation(0, 360, Animation.ABSOLUTE, Animation.ABSOLUTE, Animation.ABSOLUTE, Animation.RELATIVE_TO_SELF);
rotateAnim.setDuration(5000);
rotateAnim.setRepeatCount(1);
rotateAnim.setInterpolator(new AccelerateInterpolator());
rotateAnim.setRepeatMode(Animation.REVERSE);
AnimationSet animationSet = new AnimationSet(true);
animationSet.addAnimation(scaleAnim);
animationSet.addAnimation(rotateAnim);
ivDH.startAnimation(animationSet);
}
}
You will have to change some parameters. Hope it helps
I'm creating an application that uses an ImageSwitcher to show some images. I want to show arrows on either side of the screen in addition to a button on the bottom whenever a user has touched the screen or switched images. Just like you'll see when viewing screenshots for an application in Android Market.
So far I've had my activity implement OnGestureListener, and I've created an AsyncTask that fades in, sleeps for 1 seconds then fades out again whenever the ACTION_UP event is triggered. The problem is that I want to remove an arrow if the user flings to another image. There's three images.
Here's an exerpt of my code.
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
new FadeInOutButtons().execute();
}
return mGesture.onTouchEvent(event);
}
private void fadeOutAll() {
Animation fadeOut = AnimationUtils.loadAnimation(
MyActivity.this, android.R.anim.fade_out);
mButtonHolder.startAnimation(fadeOut);
mButtonHolder.setVisibility(View.GONE);
if (mRightArrow.getVisibility() == View.VISIBLE) {
mRightArrow.startAnimation(fadeOut);
mRightArrow.setVisibility(View.GONE);
}
if (mLeftArrow.getVisibility() == View.VISIBLE) {
mLeftArrow.startAnimation(fadeOut);
mLeftArrow.setVisibility(View.GONE);
}
}
private class FadeInOutButtons extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
fadeOutAll();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
Animation fadeIn = AnimationUtils.loadAnimation(
MyActivity.this, android.R.anim.fade_in);
mButtonHolder.startAnimation(fadeIn);
mButtonHolder.setVisibility(View.VISIBLE);
final int sz = mImages.size();
if (sz > 1) {
if (mPosition < sz - 1) {
mRightArrow.startAnimation(fadeIn);
mRightArrow.setVisibility(View.VISIBLE);
}
if (mPosition > 0) {
mLeftArrow.startAnimation(fadeIn);
mLeftArrow.setVisibility(View.VISIBLE);
}
}
super.onPreExecute();
}
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
final int sz = mImages.size();
if (sz > 1) {
if (velocityX < 0 && mPosition < sz - 1) {
mInactive = mActive;
mActive = (ImageView) mSwitcher.getNextView();
mActive.setImageResource(mImages.get(++mPosition));
mSwitcher.showNext();
} else if (velocityX > 0 && mPosition > 0) {
mInactive = mActive;
mActive = (ImageView) mSwitcher.getNextView();
mActive.setImageResource(mImages.get(--mPosition));
mSwitcher.showPrevious();
}
}
mInactive.setImageURI(null);
return true;
}
Have any of you done anything like this before? How can I make only the left arrow disappear when the third image is focused, and only the right one when the first is... And so on... ? I've been stuck on this for an hour.
Thanks!
Sorry about the formatting.
Firstly, don't use an AsyncTask if you're not actually doing any background work (sleeping doesn't count as work!). Use a Handler attached to the UI thread and postDelayed() to it.
WORKING EXAMPLE OF FADING VIEWS IN AND OUT
Firstly, your layout main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageSwitcher
android:id="#+id/imageSwitcher"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<Button android:id="#+id/prev"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Previous"
/>
<Button android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Next"
/>
</RelativeLayout>
Yes I'm using buttons rather than imageviews, just to keep the example simple.
Now the fade in and fade out animations:
fade_in.xml:
fade_out.xml:
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="#android:anim/accelerate_interpolator"
android:fromAlpha="1.0"
android:toAlpha="0.0"
android:duration="500"
android:fillAfter="true"/>
Finally, some actual code for your main activity:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;
public class MainActivity extends Activity implements ViewFactory, OnTouchListener {
ImageSwitcher imageSwitcher;
View prev,next;
Handler handler = new Handler();
static final int[] images = {
R.drawable.pic1,
R.drawable.pic2,
R.drawable.pic3
};
int currentImageIndex = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageSwitcher = (ImageSwitcher)findViewById(R.id.imageSwitcher);
imageSwitcher.setFactory(this);
imageSwitcher.setOnTouchListener(this);
prev = findViewById(R.id.prev);
next = findViewById(R.id.next);
setCurrentImage();
scheduleHideButtons();
}
private void setCurrentImage() {
imageSwitcher.setImageResource(images[currentImageIndex]);
}
private void scheduleHideButtons() {
handler.removeCallbacks(hideButtonsRunnable);
handler.postDelayed(hideButtonsRunnable, 3000);
}
private Runnable hideButtonsRunnable = new Runnable() {
#Override public void run() {
fadeButtons(false);
}
};
private void fadeButtons(final boolean fadeIn) {
if (fadeIn) {
scheduleHideButtons();
}
Animation anim = AnimationUtils.loadAnimation(this, fadeIn?R.anim.fade_in:R.anim.fade_out);
prev.startAnimation(anim);
next.startAnimation(anim);
anim.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationEnd(Animation animation) {
prev.setVisibility(fadeIn?View.VISIBLE:View.GONE);
next.setVisibility(fadeIn?View.VISIBLE:View.GONE);
}
#Override public void onAnimationRepeat(Animation animation) { }
#Override public void onAnimationStart(Animation animation) { }
});
}
#Override
public View makeView() {
ImageView imageView = new ImageView(this);
imageView.setBackgroundColor(0xFF000000);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(
ImageSwitcher.LayoutParams.FILL_PARENT,
ImageSwitcher.LayoutParams.FILL_PARENT));
return imageView;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_DOWN) {
if (prev.getVisibility()==View.GONE) {
fadeButtons(true);
}
else {
scheduleHideButtons();
}
}
return false;
}
}