Android making a button fade in and out continuously - java

I am trying to get a button to fade in and out continuously and I cant seem to figure it out.
In the OnCreate:
Button playbtn =(Button) findViewById(R.id.playbutton);
Animation myFadeInAnimation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.tween);
playbtn.startAnimation(myFadeInAnimation);
tween xml file:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:fromAlpha="0.0"
android:toAlpha="1.0"
android:duration="1000"
android:repeatMode="reverse"
android:repeatCount="infinite" />
</set>
Thanks for your help.

You can do this:
private void fadeIn() {
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mButton, "alpha", 0f, 1f);
objectAnimator.setDuration(500L);
objectAnimator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
fadeOut();
}
});
objectAnimator.start();
}
private void fadeOut() {
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mButton, "alpha", 1f, 0f);
objectAnimator.setDuration(500L);
objectAnimator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
fadeIn();
}
});
objectAnimator.start();
}
You can improve by consolidating both methods into a single one by keeping track of the state (fading in, fading out). You should also add a function to cancel the animation (you can return the animator from these functions and then call cancel on it).
Edit: to cancel, you can do this - create a member variable that holds your current animator, then simply can cancel on it:
private ObjectAnimator objectAnimator;
private void fadeOut() {
objectAnimator = ObjectAnimator.ofFloat(mButton, "alpha", 1f, 0f);
objectAnimator.setDuration(500L);
objectAnimator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
fadeIn();
}
});
objectAnimator.start();
}
private void cancelAnimator() {
if (objectAnimator != null) {
objectAnimator.cancel();
objectAnimator = null;
}
}

Your code works perfectly for me..
also you can do button fade in and out continuously in java Using
myFadeInAnimation .setRepeatCount(Animation.INFINITE);
Hope this will helps you

Related

Visual bug with native plugin animation in Ionic 4 Capacitor

I'm currently working in a custom android native plugin for Capacitor. The plugin consists in an app's footer which is working fine except for a hiding animation.
The problem is I'm changing the WebView margin everytime the footer is being shown/hide, which makes a black(sometimes is orange, probably because is one of app's main colors) bar appears in the space occupied by the footer. Black bar disappears once the animation ends.
I've tried changing the WebView margin at animation start/end and the result is the same.
Thanks in advance guys, here is some code.
Animation XML:
<translate
android:duration="150"
android:fromYDelta="0"
android:toYDelta="100%" />
WebView margin function:
private void changeWebViewMargin(float pixels) {
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) wb.getLayoutParams();
params.setMargins(0, 0, 0, (int) dpTopixel(getContext(), pixels));
wb.setLayoutParams(params);
wb.requestLayout();
}
Hide function:
#PluginMethod()
public void hide(PluginCall call) {
Boolean animated = call.getBoolean("animated");
if (animated == null) {
animated = false;
}
final boolean finalAnimated = animated;
this.getBridge().getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (finalAnimated && footer.getVisibility() == View.VISIBLE) {
changeWebViewMargin(0f);
Animation myAnim = AnimationUtils.loadAnimation(getBridge().getContext(), R.anim.hide_footer);
myAnim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
footer_img.setVisibility(View.INVISIBLE);
footer.setVisibility(View.INVISIBLE);
btn3.setVisibility(View.INVISIBLE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
footer.startAnimation(myAnim);
footer_img.startAnimation(myAnim);
btn3.startAnimation(myAnim);
} else {
footer_img.setVisibility(View.INVISIBLE);
footer.setVisibility(View.INVISIBLE);
btn3.setVisibility(View.INVISIBLE);
changeWebViewMargin(0f);
}
}
});
}
Instead of working with margins try using WindowInsets:
ViewCompat.setOnApplyWindowInsetsListener(wb, (v, insets) -> {
((ViewGroup.MarginLayoutParams) v.getLayoutParams()).bottomMargin =
insets.getSystemWindowInsetTop() + (int) dpTopixel(getContext(), pixels);
return insets.consumeSystemWindowInsets();
});

How would I animate multiple views at the same time over different points?

I'm quite new to Android Studio, and I would like to animate multiple images at the same time, over multiple coordinates.
Let's say I would like to move image A from 0/0 to 100/100, and then to 200/200; at the same time (eg. by the click of a button), image B shall be moved from 0/100 to 100/100, and then to 200/100. All with simple translations.
(As a plus, I would like to be able to set the duration of the movements independently.)
When the animations have finished, there should be an event (somthing like OnAnimationFinish?) to trigger other things, like enabling the start button again.
What would be the most effective way to do this? I know there is an AnimationSet in Android to store multiple animations, but I don't know if this is helpful here.
Thanks in advance!
You can use ObjectAnimator with AnimatorSet to play multiple animations simultaneously with proper listeners.
For example():
val imageXAnimator = ObjectAnimator.ofFloat(imageView, "translationX", translateX)
val imageYAnimator = ObjectAnimator.ofFloat(imageView, "translationY", translateY)
val imageAlphaAnimator = ObjectAnimator.ofFloat(imageView, "alpha", if (reverse) 0F else 1F)
val animationSet = AnimatorSet()
animationSet.playTogether(
imageXAnimator,
imageYAnimator,
imageAlphaAnimator)
animationSet.interpolator = DecelerateInterpolator()
animationSet.duration = 1000
animationSet.addListener(
onStart = {
//When animation is started
},
onEnd = {
//When animation finishes
}
)
animationSet.start()
Or a simple extension in kotlin which can be called on a specific View:
inline fun View.animateTranslationY(translationY: Float, duration: Long = 1000, startDelay: Long = 0) {
val translationYAnimator = ObjectAnimator.ofFloat(this, "translationY", translationY)
translationYAnimator.duration = duration
translationYAnimator.startDelay = startDelay
translationYAnimator.interpolator = LinearInterpolator()
translationYAnimator.addAnimatorListener(
onStart = { },
onEnd = { }
)
translationYAnimator.start()
}
You can use the "View.animate()" method that allow you to access to its sub-methods and events to manage all these stuff. You just have to call "animate()" on a View (TextView, ImageView, EditBox, etc..) and then call its sub-methods to decide what kind of animation to perform: motion, rotation, changing transparency, etc... For each animation you can set a listener that will be called at Start and/or at the End of animation.
Consider these two methods for both views
private void animateFirstView(final ImageView first, long durationFirst, final long durationSecond) {
first.setTranslationX(0);
first.setTranslationY(0);
first.animate().translationX(100).translationY(100).setDuration(durationFirst).setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
first.animate().translationY(200).translationX(200).setDuration(durationSecond).setListener(null).setInterpolator(new LinearInterpolator()).start();
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
}).setInterpolator(new LinearInterpolator()).start();
}
private void animateSecondView(final ImageView second, long durationFirst, final long durationSecond) {
second.setTranslationX(0);
second.setTranslationY(100);
second.animate().translationX(100).translationY(100).setDuration(durationFirst).setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
second.animate().translationY(200).translationX(100).setDuration(durationSecond).setListener(null).setInterpolator(new LinearInterpolator()).start();
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
}).setInterpolator(new LinearInterpolator()).start();
}
You can do this:
private void playAnimation(final View view, final int endRangeY) {
view.animate().translationY(endRangeY) //endRangeY where you want to end the animation
.alpha(0.0f)
.setDuration(3000)
.setListener(new AnimatorListenerAdapter() {
#Override public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
}
});
}

How to make method when Value Animator end?

as i read in here : http://developer.android.com/reference/android/animation/ValueAnimator.html
i still dont understand how to make onAnimationEnd listener or something to do when ValueAnimator animation end. there is a part in there said:
Anyone can explain with some example code? Thank you!
You can do something like
ValueAnimator anim = ValueAnimator.ofInt(progress, seekBar.getMax());
anim.setDuration(Utility.setAnimationDuration(progress));
anim.addUpdateListener(new AnimatorUpdateListener()
{
#Override
public void onAnimationUpdate(ValueAnimator animation)
{
int animProgress = (Integer) animation.getAnimatedValue();
seekBar.setProgress(animProgress);
}
});
anim.addListener(new AnimatorListenerAdapter()
{
#Override
public void onAnimationEnd(Animator animation)
{
// done
//your stuff goes here
}
});
anim.start();

Animate SpannableStringBuilder with ObjectAnimator doesn't animate

I have been trying to animate a spannablestringbuilder. However, I get this message from the Devices Logcat: "PropertyValuesHolder﹕ Method setAlpha() with type float not found on target class class".
Any ideas of how to animate a pure string at all?
Code of what I have been doing:
private static void fadeEnhancedText(Context context,TextView labText, TextView labEnchangedText,
int defaultColor) {
//animation add objectanimation
SpannableStringBuilder mSpannableStringBuilder=
new SpannableStringBuilder(labEnchangedText
.getText().toString());
mSpannableStringBuilder.setSpan(mForegroundColorSpan, mMatcher.start(),
mMatcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
labText.setText(labEnchangedText.getText().toString());
labText.setVisibility(View.GONE);
//TODO spannable problem fader doesn't work fully
labEnchangedText.setText(mSpannableStringBuilder, TextView.BufferType.SPANNABLE);
mAnimationSet.play(fadeIn(labEnchangedText,mSpannableStringBuilder)).
after(fadeOut(labEnchangedText,
labText,
defaultColor,mSpannableStringBuilder));
mAnimationSet.start();
}
private static ObjectAnimator fadeIn(TextView textView, SpannableStringBuilder spannableStringBuilder)
{
ObjectAnimator animation = ObjectAnimator.ofFloat(spannableStringBuilder.getSpans(mMatcher.start(),
mMatcher.end(),textView.getClass()), "alpha",0f,1f);
animation.setDuration(300);
return animation;
}
private static ObjectAnimator fadeOut(final TextView textView, final TextView currentView, final int defaultColor,
final SpannableStringBuilder spannableStringBuilder)
{
//textView.setTextColor(Color.rgb(177, 24, 46));
ObjectAnimator animation = ObjectAnimator.ofFloat(spannableStringBuilder.getSpans(mMatcher.start(),
mMatcher.end(),textView.getClass()), "alpha",1f,0f);
animation.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
textView.setTextColor(defaultColor);
currentView.setVisibility(View.VISIBLE);
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
animation.setRepeatCount(4);
animation.setDuration(300);
return animation;
}
TextView, the type returned for the spans in the call to getSpans (you specify the type as TextView), does not have a setAlpha method (nor a getAlpha method). Also, I'm not sure how ObjectAnimator likes arrays, but I haven't tried it.
Have a look at Android Transparent TextView? for TextView transparency.
It might also be possible to use HTML to style the text: How to display HTML in TextView? or see the string resources guide: http://developer.android.com/guide/topics/resources/string-resource.html#StylingWithHTML

Slide In and Slide Out animation for a layout

I have a LinearLayout, I am dynamically adding TextView, ImageView to that LinearLayout, now I have added OnClickListener to these TextViews and ImageViews.
I have an arraylist which has 10 items in it, using a for loop I am getting each value and displaying, since it's quiz app I have next and previous buttons, when I click on that I am displaying items one by one from the arraylist.Now I need slide In and slide Out animation to apply to this Linear Layout.
I have seen this :
Link 1
Link 2
and also I have tried this
slideIn = new TranslateAnimation(
TranslateAnimation.RELATIVE_TO_PARENT, 1.0f,
TranslateAnimation.RELATIVE_TO_PARENT, 0.0f,
TranslateAnimation.RELATIVE_TO_PARENT, 0.0f,
TranslateAnimation.RELATIVE_TO_PARENT, 0.0f);
slideIn.setDuration(500);
slideOut = new TranslateAnimation(
TranslateAnimation.RELATIVE_TO_PARENT, 0.0f,
TranslateAnimation.RELATIVE_TO_PARENT, -1.0f,
TranslateAnimation.RELATIVE_TO_PARENT, 0.0f,
TranslateAnimation.RELATIVE_TO_PARENT, 0.0f);
slideOut.setDuration(500);
But not working please help on this.
EDIT:
Problem: I have applied this to the linear layout but what happens is that when i click on next button current question will slide left and a blank screen then it will slide in and display next question, but I want as soon as the current question slides out it should be followed by next question.
If your layouts are having identical content, create two layouts inside a view flipper.
Load first view with data and show it.
When user clicks next or previous, load next view with data and keep a flag to show that 2nd view is now visible and show it with animation.
Now onwards load the appropriate views with data based on the flag values and call shownext().
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainFlipper = (ViewFlipper) findViewById(R.id.flipper);
firstLayout = (LinearLayout) findViewById(R.id.layout1);
secondLayout = (LinearLayout) findViewById(R.id.layout2);
findViewById(R.id.btnPrevious).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
showPrevious();
}
});
findViewById(R.id.btnNext).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
showNext();
}
});
}
private void showNext() {
mainFlipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in_left));
mainFlipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_out_right));
flip();
}
private void showPrevious() {
mainFlipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in_right));
mainFlipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_out_left));
flip();
}
private void flip() {
if(isFirstVisible) {
isFirstVisible = false;
secondLayout.removeAllViews();
secondLayout.addView(getTextView("Second"));
} else {
isFirstVisible = true;
firstLayout.removeAllViews();
firstLayout.addView(getTextView("First"));
}
mainFlipper.showNext();
}
private TextView getTextView(String txt) {
TextView txtView = new TextView(this);
txtView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
txtView.setText(txt);
return txtView;
}
Use this xml in res/anim/
leftright.xml
This is for left to right animation:
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate android:fromXDelta="-100%" android:toXDelta="0%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="700"/>
</set>
use this in your java code
Handler handler = new Handler();
Runnable runnable = new Runnable(){
{
public void run()
{
item[i].setInAnimation(AnimationUtils.loadAnimation(this,R.anim.leftright.xml));
i=i+1;
handler.postDelayed(this,5000);
}
};handler.postDelayed(runnable,5000);

Categories