I have an ImageView and I want it to appear 2 seconds after the code is run. I've tried this code but unfortunately it didn't do anything.
ImageView aniView = (ImageView) findViewById(R.id.imageView1);
float dest = 1;
if (aniView.getAlpha() <= 0) {
dest = 0;
System.out.println("F");
}
ObjectAnimator animation3 = ObjectAnimator.ofFloat(aniView,
"alpha", dest);
animation3.setDuration(5000);
animation3.start();
There is no need for any Handler, CountDownTimer or any other direct thread manipulation.
Android built in classes like ObjectAnimator or ViewPropertyAnimator have all needed methods in their API.
Using ObjectAnimator:
private static void showImageViewObjectAnimator(#NonNull final ImageView imageView) {
imageView.setAlpha(0f);
final ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(imageView, "alpha", 0f, 1f);
objectAnimator.setStartDelay(TimeUnit.SECONDS.toMillis(2));
objectAnimator.setDuration(TimeUnit.SECONDS.toMillis(5));
objectAnimator.start();
}
Using ViewPropertyAnimator:
private static void showImageViewViewPropertyAnimator(#NonNull final ImageView imageView) {
imageView.setAlpha(0f);
imageView.animate()
.alpha(1f)
.setStartDelay(TimeUnit.SECONDS.toMillis(2))
.setDuration(TimeUnit.SECONDS.toMillis(5));
//no need to call start!
}
I hope that it helps you
If I understood right what you want is this...
Create a new layout file and name it splash (or whatever you want) and put that image there and then add this code:
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
//display the image during 2 secondes,
new CountDownTimer(2000,1000){
#Override
public void onTick(long millisUntilFinished){}
#Override
public void onFinish(){
//set the new Content of your activity
YourActivity.this.setContentView(R.layout.main);
}
}.start();
//rest of the code goes here...
try using
aniView.postDelayed(new Runnable() {
#Override
public void run()
{
// your code for animation.
}
}, 2000); //2000 for 2 seconds delay.
Related
public class MainActivity extends Activity {
ValueAnimator animator;
ImageButton testImageButton;
float rad=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testImageButton = findViewById(R.id.ib_test);
testImageButton.setOutlineProvider(outlineProvider);
testImageButton.setClipToOutline(true);
animator = (ValueAnimator)
AnimatorInflater.loadAnimator(this,R.animator.radius);
animator.addUpdateListener(mListener);
}
public void clickedAnimator(View v){
animator.start();
}
public void testMe(View v){
l("testMe");
}
ValueAnimator.AnimatorUpdateListener mListener = new
ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float i= (float) valueAnimator.getAnimatedValue();
rad = i;
testImageButton.setOutlineProvider(outlineProvider);
}
};
ViewOutlineProvider outlineProvider = new ViewOutlineProvider() {
#Override
public void getOutline(View view, Outline outline) {
outline.setRoundRect(0,0,view.getWidth(),view.getHeight(),
rad*((float)view.getWidth())/2);
}
};
public void l(String s){
Log.v(getClass().getSimpleName(),s);
}
}
I am trying to animate the outline of an ImageView from Circle to Rectangle by constantly updating the ViewOutlineProvider that is set to the imageview.
Everything works fine but when the animation ends, the Image in the imageView Blinks once.
The value of rad changes from 1 to 0 in 500ms.
Hmmm, this line might help you: android:fillAfter="true"
Place this in your animation XML file inside the set attribute like:
<set [...]
android:fillAfter="true">
This helped me on a number of occasions when the animation was bugging at the end. Might work for you, might not, it's worth trying.
In my project I want use ProgressBar and I want set smoothly countdown animation.
I write below codes for smoothly animation and when set 1000ms (1s) for duration show smoothly animation, but I want set 10000ms (10s) for duration.
When set 10000ms (10s) for duration not smoothly animation and show Fragmentary countdown.
But I want set 10000ms for duration and show smoothly countdown.
public class SimpleFrag extends Fragment {
TextView toolbar_title;
RelativeLayout toolbar;
private ProgressBar progressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_simple, container, false);
ButterKnife.bind(this, view);
toolbar_title = getActivity().findViewById(R.id.toolbar_title);
toolbar = getActivity().findViewById(R.id.toolbar);
progressBar = view.findViewById(R.id.progress);
return view;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#SuppressLint("ObjectAnimatorBinding")
#Override
public void run() {
ProgressBarAnimation mProgressAnimation = new ProgressBarAnimation(progressBar, 79, 0);
mProgressAnimation.setDuration(10000);
progressBar.startAnimation(mProgressAnimation);
}
}, 50);
}
}
public class ProgressBarAnimation extends Animation {
private ProgressBar progressBar;
private float from;
private float to;
public ProgressBarAnimation(ProgressBar progressBar, float from, float to) {
super();
this.progressBar = progressBar;
this.from = from;
this.to = to;
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
float value = from + (to - from) * interpolatedTime;
progressBar.setProgress((int) value);
}
}
}
How can I it? please help me . Thanks all <3
Take what you have now, and delete your setUserVisibleHint() method and your ProgressBarAnimation class. Add this:
private void setUpObserver() {
progressBar.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
startAnimation();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
progressBar.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
else {
progressBar.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
}
private void startAnimation() {
int width = progressBar.getWidth();
progressBar.setMax(width);
ValueAnimator animator = ValueAnimator.ofInt(0, width);
animator.setInterpolator(new LinearInterpolator());
animator.setStartDelay(0);
animator.setDuration(10_000);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
int value = (int) valueAnimator.getAnimatedValue();
progressBar.setProgress(value);
}
});
animator.start();
}
Then, inside your onCreateView() method, call setUpObserver() right before you return view;
The setUpObserver() method uses an OnGlobalLayoutListener to make sure that the system waits until the ProgressBar is measured an laid out before starting the animation.
The startAnimation() method is what takes care of actually setting up and running the animation. You can modify the values passed to setStartDelay() and setDuration() as you see fit.
The trick to this solution is making sure that the maximum value for the progress bar is equal to its width, meaning that each increment of "progress" is equal to one pixel on the screen. The android framework animation takes care of making sure everything runs as smoothly as possible.
Edit
If you want to be able to control the start/end points for the animation (rather than just go from empty to full), make these changes:
Change the declaration of startAnimation() to this:
private void startAnimation(float startPercent, float endPercent)
Delete this line from inside startAnimation()
ValueAnimator animator = ValueAnimator.ofInt(0, width);
and add these lines instead:
int start = (int) (startPercent * width);
int end = (int) (endPercent * width);
ValueAnimator animator = ValueAnimator.ofInt(start, end);
Finally, call startAnimation() by passing in fractional percentages:
startAnimation(0.79f, 0.10f); // will animate from 79% to 10%
I m trying to increase the speed (duration) for the setmButton when mButton is clicked, but no results.I need to make the mButton to move from x=0 to x=100 in less seconds so i will increase the speed. The mButon animation starts from x=0 and move to x=100 in duration=10000, when i click on it i want the mButton to increase the speed to the final position.
Thank you
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void animationA() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final ImageButton mButton = (ImageButton)findViewById(R.id.Button );
assert mButton != null;
mButton.setBackgroundResource(R.drawable.Button);
ObjectAnimator mButtonAnimation= ObjectAnimator.ofFloat(mButton , "translationX", 0, -2100);
mButtonAnimation.setDuration(11000);
mButtonAnimation.setStartDelay(50);
mButtonAnimation.setRepeatCount(ObjectAnimator.INFINITE);
mButtonAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
ObjectAnimator mButtonAnimation1 = ObjectAnimator.ofFloat(mButton, "alpha", 0, 1);
mButtonAnimation1 .setDuration(90);
mButtonAnimation1 .setInterpolator(new AccelerateDecelerateInterpolator());
final AnimatorSet setmButton = new AnimatorSet();
setmButton .playTogether(mButtonAnimatiea, mButtonAnimation1 );
//setmButton .setFillAfter(true);
setmButton.start();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Handler handlermButton = new Handler();
handlermButton.postDelayed(new Runnable() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
#Override
public void run() {
setmButton.setDuration(500);
}
}, 100);
}
});
}}, 100); }
You could use ACCELERATE interpolator if you want an higher speed level near from the end or simply set the duration to a lower value so the animation will be faster.
So, I'm experimenting trying to create a circular reveal on API level 21 on a TextView but I keep getting this error. At first I thought it had something to do with the lifecycle of the fragment I was attempting it but then I just tried the same thing in an activity and it still wouldn't work.
Here's the code:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window w = getWindow();
w.setFlags(
WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS,
WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
w.setStatusBarColor(Color.parseColor("#0277bd"));
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.text);
int a = (tv.getLeft() + tv.getRight()) / 2;
int b = (tv.getTop() + tv.getBottom()) / 2;
int radius = tv.getWidth();
Animator anim = ViewAnimationUtils.createCircularReveal(tv, a, b, 0, radius);
anim.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
}
It's still early days so I can't really find any answers about this. Any ideas?
You're getting the error because the view you passed in hasn't been measured and laid out on the screen yet. ViewAnimationUtils.createCircularReveal needs the target view to be measured to calculate the animation. You'll also find that your variables a and b are always 0.
If you want to experiment, create the animation and start it within a button click listener. Here's an example using your code:
Button button = (Button) findViewById(R.id.your_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.text);
int a = (tv.getLeft() + tv.getRight()) / 2;
int b = (tv.getTop() + tv.getBottom()) / 2;
int radius = tv.getWidth();
Animator anim = ViewAnimationUtils.createCircularReveal(tv, a, b, 0, radius);
anim.start();
}
});
You can use Runnable to do the animation. The Runnable will run after the view's creation. No need to post delay.
view.post(new Runnable()
{
#Override
public void run(){
//create your anim here
}
});
Or you can do this.
tv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
tv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
tv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
Animator anim = ViewAnimationUtils.createCircularReveal(tv, a, b, 0, radius);
anim.start();
}
});
Adding GlobalLayoutListener to wait for the view to be inflated worked for me.
Or you can do this.
tv.postDelayed(new Runnable() {
#Override
public void run() {
//start your animation here
}
}, 1000);
How to animate multiple objects one by one after some intervals android
i am using this code for animation
for (int y = 0; y < 10; y++) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
Toast.makeText(ProjectFirstActivity.this, y + "",
Toast.LENGTH_SHORT).show();
ObjectAnimator oa = ObjectAnimator.ofFloat(myimageview[y],
"translationY", 0, -200);
oa.setDuration(1000);
oa.start();
}
});
}
but it is animating all in one go but i want one by one animation of my imageview please help
No need to use Threads and Handlers. Instead of that use,
objectAnimator.setStartDelay(delay);
Using that you can stop that animation for the respective 'delay'
Try this code..
int delay = 1000;
for (int y = 0; y < 10; y++) {
Toast.makeText(ProjectFirstActivity.this, y + "",
Toast.LENGTH_SHORT).show();
ObjectAnimator oa = ObjectAnimator.ofFloat(myimageview[y],
"translationY", 0, -200);
oa.setDuration(1000);
oa.setStartDelay(delay);
oa.start();
delay = delay+1000;
}
You can use for loop to generate AnimatorSet and then play them sequentially using set.playSequentially(yourAnimatorSetListHere);
I haven't used list in below mentioned snippet.
AnimatorSet decSet = new AnimatorSet();
decSet.playTogether(
ObjectAnimator.ofArgb(mTextSlidetoCancel, "visibility", View.GONE, View.VISIBLE),
ObjectAnimator.ofArgb(mBtnMicActive, "visibility", View.GONE, View.VISIBLE),
ObjectAnimator.ofArgb(mChronometer, "visibility", View.GONE, View.VISIBLE));
decSet.setDuration(125);
AnimatorSet decSet2 = new AnimatorSet();
decSet2.playTogether(
ObjectAnimator.ofArgb(mBtnAttach, "visibility", View.VISIBLE, View.GONE),
ObjectAnimator.ofArgb(mBtnEmoji, "visibility", View.VISIBLE, View.GONE),
ObjectAnimator.ofArgb(mEditTExt, "visibility", View.VISIBLE, View.GONE)
);
decSet2.setDuration(125);
AnimatorSet set = new AnimatorSet();
set.playSequentially(decSet2,decSet);
set.start();
Try out this way!
public Integer[] Imgid = {R.drawable.anim2, R.drawable.anim3,
R.drawable.anim4, R.drawable.anim5}; // your image array.
Animation anim;
Handler handler;
ImageView iv;
int count;
Runnable galleryAnimRunnable;
Inside onCreate
iv= (ImageView)findViewById(R.id.imagetype);
handler = new Handler();
galleryAnimRunnable = new Runnable() {
public void run() {
if(count==Imgid.length){
//do any action
}
else{
anim = AnimationUtils.loadAnimation(AnimationScreen.this, R.anim.fade_out); // load your desire animation.
iv.setBackgroundResource(Imgid[count]);
iv.setAnimation(anim);
count++;
handler.postDelayed(galleryAnimRunnable, 300); //set your desire delay time.
}
}
};
Your sleep call isn't helping because when one posted UI job goes to sleep, then next one starts and goes to sleep immediately following that, and so on. Then the first job wakes up and runs, followed closely by the second job awakening and running, etc.
If you want the sleep to help you need to wait before posting each job, which could be as simple as something like the following:
for (int y = 0; y < 10; y++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ProjectFirstActivity.this, y + "",
Toast.LENGTH_SHORT).show();
ObjectAnimator oa = ObjectAnimator.ofFloat(myimageview[y],
"translationY", 0, -200);
oa.setDuration(1000);
oa.start();
}
});
}
EDIT: Although the above explains why you were having problems, I would recommend going with something like the answer posted by Jgdsh Seerm using setStartDelay().
Try this way!
ImageView image1;
public int currentimageindex1=0;
Timer timer;
TimerTask task;
private Animation animation1;
private Animation animation2;
int img[] = {R.drawable.aa, R.drawable.bb,
R.drawable.cc,R.drawable.dd,R.drawable.ee,R.drawable.ff,R.drawable.gg,
R.drawable.hh};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Handler mHandler = new Handler();
// Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
public void run() {
AnimateandSlideShow();
}
};
int delay = 1000; // delay for 1 sec.
int period = 4000; // repeat every 4 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
mHandler.post(mUpdateResults);
}
}, delay, period);
}
public void onClick(View v) {
finish();
android.os.Process.killProcess(android.os.Process.myPid());
}
/**
* Helper method to start the animation on the splash screen
*/
private void AnimateandSlideShow() {
image1 = (ImageView)findViewById(R.id.imageView1);
image1.setImageResource(img[currentimageindex1%img.length]);
currentimageindex1++;
}