Change button function during animation - java

I need to change button function during animation playback
#JulianoNunesSilvaOliveria said that I can change it by flag variable :
boolean something = false; if (something) { doA(); something = false;} else { doB(); }
but how i use it?
i start animation like this
oilcan.startAnimation(seq1)

You can use AnimatorListener:
oilcan.animate().setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
something = false;
}
#Override
public void onAnimationEnd(Animator animation) {
something = true;
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}

Related

Detect when animation is done

So this is my spin the bottle animation:
public static final Random RANDOM = new Random();
private int lastAngle = -1;
private ImageView bottle;
private void spinTheBottle() {
int angle = RANDOM.nextInt(3600 - 360) + 360;
float pivotX = bottle.getWidth() / 2;
float pivotY = bottle.getHeight() / 2;
final Animation animRotate = new RotateAnimation(lastAngle == -1 ? 0 : lastAngle, angle, pivotX, pivotY);
lastAngle = angle;
animRotate.setDuration(1500);
animRotate.setFillAfter(true);
bottle.startAnimation(animRotate);
}
How can I detect when the animation is done? I tried adding Animator.AnimatorListener, but that does not execute at all:
Animator.AnimatorListener listener = new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
Toast.makeText(FlasketutenActivity.this, "onAnimationStart", Toast.LENGTH_SHORT).show();
}
#Override
public void onAnimationEnd(Animator animation) {
Toast.makeText(FlasketutenActivity.this, "onAnimationEnd", Toast.LENGTH_SHORT).show();
}
#Override
public void onAnimationCancel(Animator animation) {
Toast.makeText(FlasketutenActivity.this, "onAnimationCancel", Toast.LENGTH_SHORT).show();
}
#Override
public void onAnimationRepeat(Animator animation) {
Toast.makeText(FlasketutenActivity.this, "onAnimationRepeat", Toast.LENGTH_SHORT).show();
}
};
Any tips?
It looks like you're creating the listener, but not assigning it to your animation. Try calling setAnimationListener on your animation object like this:
animRotate.setAnimationListener(new Animation.AnimationListener() {
//Listener methods
});
The first.Keep the ImageView witch and height above of zero at time
rotateAnimation.setDuration(1500);
rotateAnimation.setFillAfter(true);
rotateAnimation.setFillEnabled(true);
rotateAnimation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
Log.d(TAG, "onAnimationStart: ");
}
#Override
public void onAnimationEnd(Animation animation) {
Log.d(TAG, "onAnimationEnd: ");
}
#Override
public void onAnimationRepeat(Animation animation) {
Log.d(TAG, "onAnimationRepeat: ");
}
});
view.startAnimation(rotateAnimation);
it is working in my project.
But I use the animation always in xmls,it is Easy to operate and relatively by code.
Animation and Animator is not a same things.
That's all.
Assign your listener that you have created to the animation
animRotate.setAnimationListener(listener);

How to start new activity from another activity without button click in android

I made a simple game, where whenever my object reaches end of the screen current activity stops and another activity stars.
I have created a simple boolean method called collisionDetection() which checks whether an object is hitting the end of the screen or not. However, I don't know where I should use that method collisionDetection() .
Should I check for collision at onResume? And when collision is detected, how to start another activity and stop the main one?
My class for first activity
public class ZmijicaCrtanje extends AppCompatActivity implements View.OnTouchListener{
ZmijicaSV zmija;
private static int score=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
zmija=new ZmijicaSV(this);
zmija.setOnTouchListener(this);
setContentView(zmija);
}
#Override
protected void onPause() {
super.onPause();
zmija.pause();
}
#Override
protected void onResume() {
super.onResume();
zmija.resume();
}
#Override
public boolean onTouch(View v, MotionEvent event) {
boolean up=zmija.sp.isUp();
boolean right=zmija.sp.isRight();
boolean down=zmija.sp.isDown();
boolean left=zmija.sp.isLeft();
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
if(up) {
zmija.sp.setUp(false);
zmija.sp.setRight(true);
update();
break;
}
if(right) {
zmija.sp.setRight(false);
zmija.sp.setDown(true);
update();
break;
}
if(down) {
zmija.sp.setDown(false);
zmija.sp.setLeft(true);
update();
break;
}
if(left) {
zmija.sp.setLeft(false);
zmija.sp.setUp(true);
update();
break;
}
}
return true;
}
public void update()
{
score++;
}
public int getScore()
{
return score;
}
}
public class ZmijicaSV extends SurfaceView implements Runnable {
private boolean Collision;
Thread t=null;
Pravougaonik pr;
SurfaceHolder holder;
boolean isRunning=false;
SnakeParts sp;
ZmijicaCrtanje zc;
public ZmijicaSV(Context context) {
super(context);
holder=getHolder();
pr=new Pravougaonik(context);
sp=new SnakeParts();
zc=new ZmijicaCrtanje();
Collision=false;
}
public void run()
{
Paint p=new Paint();
p.setColor(Color.BLUE);
p.setStyle(Paint.Style.FILL);
while(isRunning)
{
if(!holder.getSurface().isValid()) {
continue;
}
Canvas c=holder.lockCanvas();
c.drawColor(Color.BLACK);
sp.Draw(c);
pr.onDraw(c);
sp.update();
drawText(c);
holder.unlockCanvasAndPost(c);
try {
t.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void resume()
{
isRunning=true;
t=new Thread(this);
t.start();
}
public void pause()
{
isRunning=false;
while(true)
{
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
t=null;
}
public void drawText(Canvas canvas)
{
Paint paint=new Paint();
paint.setColor(Color.WHITE);
paint.setTextSize(50);
paint.setTypeface(Typeface.create(Typeface.DEFAULT,Typeface.BOLD));
canvas.drawText("Score:"+zc.getScore(),getWidth()-230,getHeight()-25,paint);
}
public boolean checkCollision()
{
if((sp.getHeadX()<-1)||(sp.getHeadX()>getWidth())||(sp.getHeadY()>getHeight())||(sp.getHeadY()<-1))
Collision=true;
return Collision;
}
}
Put the collisionDetection() method in your public void update() method like
public void update()
{
score++;
collisionDetection();
}
And when collition is detected in collisionDetection() start next activity by Intent like
Intent next=new Intent(this.class,your_class_for_secondactivity.class);
startActivity(next);

Gmail like Flip animation get's interrupted if second animation starts

I have implemented an Android listview with flip checkboxes (GMail style) as shown here: http://techiedreams.com/gmail-like-flip-animated-multi-selection-list-view-with-action-mode/
The problem I have (even in the source code example): If there are multiple items I click/check in a fast sequence, the previous animation stops and will be restared. In other words, the previous animation does not finish and is interrupted by the second one.
Simple download the source code and try it on your own. In comparisson to gmail all animations, no matter how fast I'm clicking, are performed from the start to the end.
I can't find the piece of code in the demo source code to change this behaviour.
Any hints?
Thanks in advance :)
This is the closest I could get to Gmail's flip animation:
In the getView() method (I'm using contextual action mode):
holder.check.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mActionMode == null) {
checked = new SparseBooleanArray(alllists.size());
mActionMode = ((Activity) getActivity()).startActionMode(mActionModeCallback);
animateRow(position);
checked.put(position, true);
mActionMode.setTitle("1");
mActionMode.getMenu().getItem(0).setVisible(true);
} else {
animateRow(position);
if (checked.get(position)) {
checked.put(position, false);
if (checked.indexOfValue(true) < 0) {
mActionMode.finish();
} else {
mActionMode.setTitle(String.valueOf(getCheckedCount()));
}
} else {
checked.put(position, true);
mActionMode.setTitle(String.valueOf(getCheckedCount()));
}
}
}
}
);
Then the animateRow() method:
private void animateRow(final int position) {
if (position >= listView.getFirstVisiblePosition() && position <= listView.getLastVisiblePosition()) {
Log.i("animateRow", String.valueOf(position));
ScaleAnimation anim = new ScaleAnimation(1, 0, 1, 1, Animation.RELATIVE_TO_SELF, 0.5f, 0, 0);
anim.setDuration(150);
anim.setRepeatCount(1);
anim.setRepeatMode(Animation.REVERSE);
viewa = listView.getChildAt(position - listView.getFirstVisiblePosition());
final Button chkButton = (Button) viewa.findViewById(R.id.logo);
if (checked.get(position)) {
anim.setAnimationListener(
new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
Log.i("anim" + position, "Start");
}
#Override
public void onAnimationRepeat(Animation animation) {
Log.i("anim" + position, "Repeat" + animation.getRepeatCount());
viewa.setBackgroundResource(R.color.row_background);
chkButton.setBackgroundResource(R.color.button_background);
chkButton.setText(String.valueOf(alllists.get(position).itemsCount));
}
#Override
public void onAnimationEnd(Animation animation) {
Log.i("anim" + position, "END");
}
}
);
chkButton.startAnimation(anim);
} else {
anim.setAnimationListener(
new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
Log.i("anim" + position, "Start");
}
#Override
public void onAnimationRepeat(Animation animation) {
viewa.setBackgroundResource(R.color.checked_row_background);
chkButton.setBackgroundResource(R.color.checked_button_background);
chkButton.setText("✓");
}
#Override
public void onAnimationEnd(Animation animation) {
Log.i("anim" + position, "END");
}
}
);
chkButton.startAnimation(anim);
}
}
}
I hope it helps.. :)
Now you can forget that method to flip a view, since I've developed a new library FlipView fully customizable, this is exactly what you want. You will be able to swap any kind of views and layouts with any kind of animation you desire.
Please have a look.

Android java thread sleep sample

I'm doing a simple animation app in Android. This is the scenario. I have a button and 4 textviews. When the user clicks the button, the first textview should begin animating (blinking effect) and next the second textview and so on. This is what I've tried so far:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
btGo.setEnabled(false);
glowCircuit2();
glowCircuit3();
glowCircuit4();
}
private void glowCircuit2() {
new Thread(new Runnable()
{
#Override
public void run()
{
while (!Thread.interrupted())
try
{
Thread.sleep(3000);
runOnUiThread(new Runnable() // start actions in UI thread
{
#Override
public void run()
{
// this action have to be in UI thread
tvCircuit2.setCompoundDrawablesWithIntrinsicBounds(0,
R.drawable.activecircuit, 0, 0);
tvCircuit2.startAnimation(animBlink);
}
});
}
catch (InterruptedException e)
{
// ooops
}
}
}).start(); // the while thread will start in BG thread
}
private void glowCircuit3() {
new Thread(new Runnable()
{
#Override
public void run()
{
while (!Thread.interrupted())
try
{
Thread.sleep(3000);
runOnUiThread(new Runnable() // start actions in UI thread
{
#Override
public void run()
{
// this action have to be in UI thread
tvCircuit3.setCompoundDrawablesWithIntrinsicBounds(0,
R.drawable.activecircuit, 0, 0);
tvCircuit3.startAnimation(animBlink);
}
});
}
catch (InterruptedException e)
{
// ooops
}
}
}).start(); // the while thread will start in BG thread
}
private void glowCircuit4() {
new Thread(new Runnable()
{
#Override
public void run()
{
while (!Thread.interrupted())
try
{
Thread.sleep(3000);
runOnUiThread(new Runnable() // start actions in UI thread
{
#Override
public void run()
{
// this action have to be in UI thread
tvCircuit4.setCompoundDrawablesWithIntrinsicBounds(0,
R.drawable.activecircuit, 0, 0);
tvCircuit4.startAnimation(animBlink);
}
});
}
catch (InterruptedException e)
{
// ooops
}
}
}).start(); // the while thread will start in BG thread
}
I'm getting the blinking effect but I'm getting the simultaneous effect. What I want is to wait for each textview to animate, not animate at the same time. Do you have any clever idea to do this? Help is much appreciated. Thanks.
you are using Threads here, you never know which thread gets priority first and which will get started. I suggest you to using handler, create different message id to send empty message to handler, Android do something like this :
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
btGo.setEnabled(false);
handler.sendEmptyMessage(1);
}
Handler handler = new Handler(){
onHandle(Messsage msg)
{
switch (msg.what)
{
case 1 : glowCircuit2();
handler.sendEmptyMessage(2);
break;
case 2: glowCircuit3();
handler.sendEmptyMessage(3);
break;
}
}
};
private void glowCircuit2(){
tvCircuit2.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.activecircuit, 0, 0);
tvCircuit2.startAnimation(animBlink);
}
change your code
glowCircuit2();
glowCircuit3();
glowCircuit4();
to this
animation.setAnimationListener(new Animation.AnimationListener()
{
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
glowCircuit2();
}
});
animation1.setAnimationListener(new Animation.AnimationListener()
{
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
glowCircuit3();
}
});
animation2.setAnimationListener(new Animation.AnimationListener()
{
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
glowCircuit4();
}
});
like this code start your third animation on second animation end and start fourth animation on third is end.

Why won't this Java Android SHOUTcast MediaPlayer app code work?

String url = "http://91.121.140.11:8000/";
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
mediaPlayer.start();
I am using Android 4.0.3 to test this and have tried it on a physical device and the emulator. The app opens but I cannot hear anything. I thought they added support for SHOUTcast streams. Have I done something wrong?
I was having the same issue so I decided simply to try it on a real device (4.0.4). It worked. Seems like an emulator issue to me.
MediaPlayer mp;
#Override
public void onCreate(){
mp = new MediaPlayer();
mp.setOnPreparedListener(this);
}
public void prepareplayer(){
mp.setDataSource(Url);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
Log.d(TAG, "Preparing..");
mp.prepareAsync();
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
Log.d(TAG, "Prepared");
mp.play();
}
I suggest you
test with other URL
try removing third line
I'm using this code for a shout cast stream works okay. Just need to add a controller using a surfaceview in XML.
private String shoutcastsource = "Your http:\\223.example.80.4003"
surfaceView = (SurfaceView)findViewById(R.id.surface);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(mediaController != null){
mediaController.show();
}
return false;
}
});
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Toast.makeText(radiostation.this,
"Media Controls active lets mash it up", Toast.LENGTH_LONG).show();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnPreparedListener(this);
try {
mediaPlayer.setDataSource(shoutcastsource);
mediaPlayer.prepare();
mediaController = new MediaController(this);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(radiostation.this,
"Radio Station off Air or no internet connection!\n" + e.toString(),
Toast.LENGTH_LONG).show();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
Toast.makeText(radiostation.this,
"You are now connected to Ukn-Radio the home of the mash up", Toast.LENGTH_LONG).show();
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(surfaceView);
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
#Override
public void start() {
mediaPlayer.start();
}
#Override
public void pause() {
mediaPlayer.pause();
}
#Override
public int getDuration() {
return mediaPlayer.getDuration();
}
#Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
#Override
public void seekTo(int pos) {
mediaPlayer.seekTo(pos);
}
#Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return false;
}
#Override
public boolean canSeekForward() {
return false;
}
#Override
public int getAudioSessionId() {
return mediaPlayer.getAudioSessionId();
}
#Override
public void onBackPressed() {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer=null;
finish();
}
}
Edit
Also make sure you allow internet access in your Android manifest:
<uses-permission android:name="android.permission.INTERNET" />

Categories

Resources