Animation in Android and Multithreading - android

In trying to add animation to ImageViews, I don't seem to get the multithreading right which is giving me incorrect results.
This is the part where I am calling the animation >>
startAnimation(gameController.getSecondImage()); // 1
...
startAnimation(gameController.getFirstImage()); // 2
...
startAnimation(gameController.getSecondImage()); // 3
...
The problem here is that when I was not creating a separate thread, for the startAnimation() function, all 3 calls happened simultaneously and everything got messed up. But still now it is not working perfectly and the 1st & 3rd calls are jumbled up.
public void startAnimation(final ImageView image1) {
final ImageView image2 = cardViewMap.get(cardSwapMap.get(image1.getId()));
Runnable animate = new Runnable() {
#Override
public void run() {
animationController.animate(image1, image2);
}
};
Thread animationThread = new Thread(animate);
animationThread.start();
try { //
animationThread.join(); //
} catch (InterruptedException e) { // Added Later
Log.d("ERROR", e.toString()); //
} //
}
I tried to experiment with join() but it didn't work out, it is giving more radical outcomes now. I thought that using join() will ensure excution of the previous calls to startAnimation() before starting a new.
EDIT: I have tracked the issue and the issue is that my startAnimation() function is being called when the main Looper is running. So it is being executed after all three calls to the function has been made. I need to ensure that startAnimation() runs at the time when I make the call, and is executed before the next call to the same function happens. Any ideas how to ensure this?

try to run this code it will help you understand a work around, once you run it it will be easier for you to understand,
make an layout name it animation_test_activity.xml code is below
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="#drawable/ic_launcher"
android:visibility="invisible" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/imageView3"
android:layout_alignParentTop="true"
android:src="#drawable/ic_launcher"
android:visibility="invisible" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/imageView3"
android:layout_alignParentTop="true"
android:src="#drawable/ic_launcher"
android:visibility="invisible" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/imageView3"
android:layout_alignParentBottom="true"
android:text="click me" />
</RelativeLayout>
now in make an activity named AnimationTest.java the code is as mentioned below.
package com.some.servewrtest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
public class AnimationTest extends Activity implements OnClickListener {
private ImageView[] imageViews = new ImageView[3];
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.animation_test_activity);
initializeUI();
}
private void initializeUI() {
// TODO Auto-generated method stub
imageViews[0] = (ImageView) findViewById(R.id.imageView1);
imageViews[1] = (ImageView) findViewById(R.id.imageView2);
imageViews[2] = (ImageView) findViewById(R.id.imageView3);
button = (Button)findViewById(R.id.button1);
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AnimationSet set = new AnimationSet(true);
TranslateAnimation[] animations = new TranslateAnimation[3];
int duration = 300;
animations[0] = createCoins(0, duration*1, 0, 0, 0, 270);
animations[1] = createCoins(1, duration*2, 0, -100, 0, 270);
animations[2] = createCoins(2, duration*3, 0, 100, 0, 270);
set.addAnimation(animations[0]);
set.addAnimation(animations[1]);
set.addAnimation(animations[2]);
set.start();
}
private TranslateAnimation createCoins(int i, int duration, int fromXDelta, int toXDelta, int fromYDelta, int toYDelta) {
// TODO Auto-generated method stub
TranslateAnimation animation = new TranslateAnimation(fromXDelta, toXDelta, fromYDelta, toYDelta);
animation.setDuration(duration+1900);
animation.setFillAfter(false);
imageViews[i].setVisibility(ImageView.VISIBLE);
imageViews[i].setAnimation(animation);
imageViews[i].setVisibility(ImageView.INVISIBLE);
return animation;
}
}
This code is working you can test it as well that you may customize the way you want to use it.
Now we have a working example we will see how did we get there,
First if you try to animate same image over and over using AnimationSet or making different TranslateAnimation reference type to same image that doesn't work because a single image tries to be at two different places virtually at the same time. So what happens is only first animation is seen and others are ignored by android it is one of the result of repeat method doesn't work in android.
To solve this what we can do is have as many Views as we need to show different animation on each one a separate View this time. It works as each animation is related to single view and they can work concurrently.
I am in no position to tell not not to go for Multi-Threading but remember you are trying to do this on UI Thread so if you have many animations in your app it will bog your app with these threads that is quite possible.
if you want to listen to an event when a particular animation is over lets say animation then do this
animation..setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
Log.d(TAG, "Animation has started");
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
Log.d(TAG, "Animation is repeat");
}
#Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
Log.d(TAG, "Animation is over");
}
});
by doing this you can start a new animation when previous is over :)

I tried and failed using Android tools. I went back and fixed it with multithreading.
Though there is a lot of other code that I changed, this is one of the important one w.r.t. my issue-
package thakur.rahul.colourmemory.controller;
import thakur.rahul.colourmemory.view.Animation.DisplayNextView;
import thakur.rahul.colourmemory.view.Animation.Flip3dAnimation;
import android.app.Activity;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
public class AnimationController implements Runnable {
private Activity activity;
private ImageView image1;
private ImageView image2;
private boolean isFirstImage = true;
private volatile static int numThread = 1;
private volatile static int threadAllowedToRun = 1;
private int myThreadID;
private volatile static Object myLock = new Object();
private volatile static boolean hasNotSlept = true;
public volatile static boolean fixForMatch = false;
public AnimationController(Activity activity, ImageView image1, ImageView image2) {
this.activity = activity;
this.image1 = image1;
this.image2 = image2;
this.myThreadID = numThread++;
}
#Override
public void run() {
synchronized (myLock) {
while (myThreadID != threadAllowedToRun)
try {
myLock.wait();
} catch (InterruptedException e) {
} catch (Exception e) {
}
animate();
if (myThreadID % 2 == 0)
if (hasNotSlept || fixForMatch)
try {
Thread.sleep(1000);
hasNotSlept = !hasNotSlept;
} catch (InterruptedException e) {
}
else
hasNotSlept = !hasNotSlept;
myLock.notifyAll();
threadAllowedToRun++;
}
}
public void animate() {
if (isFirstImage) {
applyRotation(0, 90);
isFirstImage = !isFirstImage;
} else {
applyRotation(0, -90);
isFirstImage = !isFirstImage;
}
}
private void applyRotation(float start, float end) {
final float centerX = image1.getWidth() / 2.0f;
final float centerY = image1.getHeight() / 2.0f;
final Flip3dAnimation rotation = new Flip3dAnimation(start, end, centerX, centerY);
rotation.setDuration(300);
rotation.setFillAfter(true);
rotation.setInterpolator(new AccelerateInterpolator());
rotation.setAnimationListener(new DisplayNextView(isFirstImage, image1, image2));
if (isFirstImage)
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
image1.startAnimation(rotation);
}
});
else
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
image2.startAnimation(rotation);
}
});
}
}
This is being called from the main controller as-
public void startAnimation(ImageView image1) {
ImageView image2 = cardViewMap.get(cardSwapMap.get(image1.getId()));
animationController = new AnimationController(activity, image1, image2);
animationThread = new Thread(animationController);
animationThread.start();
}
Basically, every time I need to run the animation, I make and tag the thread so I can run it in order.
Please add your answer if you have a better solution.

Related

How to fill progress bar in a specific amount of time?

I have the following splash screen for my app:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:src = "#drawable/timer_ic"
android:layout_centerInParent="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Timer"
android:textColor="#FFFFFF"
android:id="#+id/textView"
android:layout_above="#+id/imageView"
android:layout_centerHorizontal="true"
android:layout_marginBottom="51dp" />
<ProgressBar
android:id="#+id/progress_bar"
style="#android:style/Widget.ProgressBar.Horizontal"
android:layout_width="250sp"
android:layout_height="5sp"
android:progress="1"
android:layout_marginTop="82dp"
android:max="3"
android:indeterminate="false"
android:layout_below="#+id/imageView"
android:layout_centerHorizontal="true"
android:progressDrawable="#drawable/custom_progress_bar"
android:background="#808080"/>
</RelativeLayout>
The splash screen runs for 3 seconds before moving onto the next activity, which is controlled by this piece of code:
package com.awesomeapps.misael.timer;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.ProgressBar;
public class SplashScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread timer = new Thread(){
public void run(){
try{
sleep(3000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent openMainActivity= new Intent("com.awesomeapps.timer.MAINACTIVITY");
startActivity(openMainActivity);
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Like I said and as you can see the splash screeb runs for 3 seconds (3000 milliseconds). You may also notice that the splash screen has a progress bar.
My question is:
How can I fill/load the progress bad in those 3 seconds that my splash screen is running?
I guess to give my app that sort of loading effect when it first starts by filling the progress bar.
Is it possible to do this?
I would get rid of yout timer Thread and instead use ValueAnimator to animate progress bar with duration of 3 seconds
ValueAnimator animator = ValueAnimator.ofInt(0, progressBar.getMax());
animator.setDuration(3000);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation){
progressBar.setProgress((Integer)animation.getAnimatedValue());
}
});
animator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
// start your activity here
}
});
animator.start();
you can use a countdown timer for that instead of Thread or Handler
private CountDownTimer countDownTimer =
new CountDownTimer(10000, 100) {
public void onTick(long millisUntilFinished) {
progressBar.setProgress(Math.abs((int) millisUntilFinished / 100 - 100));
}
}
public void onFinish() {
// you can do your action
}
};
to start count down timer
countDownTimer.start();
new Thread(new Runnable() {
public void run() {
doWork();
startApp();
finish();
}
}).start();
}
private void doWork() {
for (int progress=1; progress<=100; progress+=1) {
try {
Thread.sleep(50); // 5 seconds
load.setProgress(progress);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void startApp() {
Intent intent = new Intent(Splash.this, MainActivity.class);
startActivity(intent);
}
Instead of having a timer that waits 3000 ms, have a timer that waits 100ms. Then increment the progress bar by 1/30th of its length each time, until you hit 100%. Then launch your main activity. The smoother you want the bar to move, the smaller your timer should be.
Try this Code
For Your Question You need to change the splash
I am Answer You to try the custom Progress bar Or you using your Progress bar also
SplashScreenActivity .java
public class SplashScreenActivity extends Activity {
private int SPLASH_TIME = 3000;
#Override
public void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
(new Handler()).postDelayed(new Runnable() {
public void run() {
Intent intent = new Intent(SplashScreenActivity.this, YouNewActivity.class);
startActivity(intent);
SplashScreenActivity.this.finish();
overridePendingTransition(R.anim.right_in, R.anim.left_out);
}
}, SPLASH_TIME);
}
#Override
public void onBackPressed() {
}
}
activity_splash.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: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"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<com.example.custom.customcircleprogressbar.CricleProgressBarCustom
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></com.example.custom.customcircleprogressbar.CricleProgressBarCustom>
</RelativeLayout>
</RelativeLayout>
CircleProgressBarCustom.java
public class CricleProgressBarCustom extends View {
//Normal dot radius
private int dotRadius = 10;
//Expanded Dot Radius
private int bounceDotRadius = 13;
//to get identified in which position dot has to expand its radius
private int dotPosition = 1;
//specify how many dots you need in a progressbar
private int dotAmount = 10;
//specify the circle radius
private int circleRadius = 50;
public CricleProgressBarCustom(Context context) {
super(context);
}
public CricleProgressBarCustom(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CricleProgressBarCustom(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
//Animation called when attaching to the window, i.e to your screen
startAnimation();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//take the point to the center of the screen
canvas.translate(this.getWidth()/2,this.getHeight()/2);
Paint progressPaint = new Paint();
progressPaint.setColor(Color.parseColor("#ff014e"));
//call create dot method
createDotInCircle(canvas,progressPaint);
}
private void createDotInCircle(Canvas canvas,Paint progressPaint) {
//angle for each dot angle = (360/number of dots) i.e (360/10)
int angle = 36;
for(int i = 1; i <= dotAmount; i++){
if(i == dotPosition){
// angle should be in radians i.e formula (angle *(Math.PI / 180))
float x = (float) (circleRadius * (Math.cos((angle * i) * (Math.PI / 180))));
float y = (float) (circleRadius * (Math.sin((angle * i) * (Math.PI / 180))));
canvas.drawCircle(x,y, bounceDotRadius, progressPaint);
}else{
// angle should be in radians i.e formula (angle *(Math.PI / 180))
float x = (float) (circleRadius * (Math.cos((angle * i) * (Math.PI / 180))));
float y = (float) (circleRadius * (Math.sin((angle * i) * (Math.PI / 180))));
canvas.drawCircle(x,y, dotRadius, progressPaint);
}
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = 0;
int height = 0;
//Dynamically setting width and height to progressbar 100 is circle radius, dotRadius * 3 to cover the width and height of Progressbar
width = 100 + (dotRadius*3);
height = 100 + (dotRadius*3);
//MUST CALL THIS
setMeasuredDimension(width, height);
}
private void startAnimation() {
BounceAnimation bounceAnimation = new BounceAnimation();
bounceAnimation.setDuration(150);
bounceAnimation.setRepeatCount(Animation.INFINITE);
bounceAnimation.setInterpolator(new LinearInterpolator());
bounceAnimation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
dotPosition++;
//when dotPosition == dotAmount , then start again applying animation from 0th positon , i.e dotPosition = 0;
if (dotPosition > dotAmount) {
dotPosition = 1;
}
}
});
startAnimation(bounceAnimation);
}
private class BounceAnimation extends Animation {
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
//call invalidate to redraw your view againg.
invalidate();
}
}
}

android pre honeycomb animation of layout

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.

I am trying to rotate imagebutton to 360 by clicking it but it can't rotate it?

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

Animation Class called inside another class

I am creating a boardgame for Android and I have an animation that I wish to do when a specific motion event occurs.
I have a Boardview class which draws on a surfaceview with bitmaps and this shows the user the board.
When a motion event happens, this code executes
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Intent animate = new Intent(Tempboardview.this, Moving.class);
animate.putExtra("xOld", oldStones.get(i).getx());
animate.putExtra("yOld", oldStones.get(i).gety());
animate.putExtra("xNew", newStones.get(i).getx());
animate.putExtra("yNew", newStones.get(i).gety());
animate.putExtra("color", 0);
startActivity(animate);
}
}
where newStones and oldStones are simply ArrayList objects and gety() and getx() return doubles.
This is my Moving class
public class Moving extends Activity {
private static final String TAG = "Animation";
double xOld = 0, yOld = 0, xNew = 0, yNew = 0, color = 0;
/** Called when the activity is first created. */#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
LayoutInflater inflater = getLayoutInflater();
addContentView(inflater.inflate(R.layout.move, null),
new ViewGroup.LayoutParams(800, 480));
final ImageView image = (ImageView) findViewById(R.id.stoneimager);
image.setVisibility(View.GONE);
image.bringToFront();
Bundle extras = getIntent().getExtras();
if (extras != null) {
xOld = extras.getDouble("xOld");
yOld = extras.getDouble("yOld");
xNew = extras.getDouble("xNew");
yNew = extras.getDouble("yNew");
color = extras.getDouble("color");
}
Animation animate = new TranslateAnimation((float) xOld, (float) xNew, (float) yOld, (float) yNew);
animate.setDuration(1000);
animate.setStartOffset(0);
animate.setInterpolator(new LinearInterpolator());
animate.setRepeatCount(0);
animate.setFillAfter(true);
animate.setZAdjustment(Animation.ZORDER_TOP);
Animation.AnimationListener listener = new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
Log.d("boardtag", "animation started");
image.setVisibility(View.VISIBLE);
image.bringToFront();
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
image.setVisibility(View.GONE);
finish();
}
};
animate.setAnimationListener(listener);
Log.d("boardtag", "animation started");
image.startAnimation(animate);
}
}
The problem is the animation is not able to take place while the board is still displayed.
I have used the android manifest to change the theme of .Moving to Transparent, but this did not work.
Any advice would be appreciated.
This is probably going to come off more harsh than I intend, but I think you are completely abusing the Intent/Activity features. You need to seriously consider redesigning your UI layer to be more closely coupled with the active Activity.
What you have above should be painfully slow since motion events are common and Activity creation and Intent dispatching is expensive (relatively). What you need is a single main "game" Activity that is tightly coupled with a SurfaceView (probably OpenGL since this has animations and it's a game). This activity would take user input (UI events) and translate them into drawing commands for your surface view directly.

Fading arrows on imageswitcher

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;
}
}

Categories

Resources