Last active
August 29, 2015 14:23
-
-
Save rocboronat/02a2ed86692e95c1cbbc to your computer and use it in GitHub Desktop.
A custom View to mimic the Material behavior for the error labels
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package at.rocboron.android.widget; | |
import android.content.Context; | |
import android.util.AttributeSet; | |
import android.widget.TextView; | |
import com.nineoldandroids.animation.ObjectAnimator; | |
import com.nineoldandroids.animation.ValueAnimator; | |
/** | |
* A simple widget to show an error. Its height will be 0 if nothing is shown, | |
* and it will be automagically animated when someones put text on it. | |
* <p/> | |
* Created by Roc Boronat ([email protected]) on 30/06/2015. | |
*/ | |
public class MaterialErrorTextView extends TextView implements ValueAnimator.AnimatorUpdateListener { | |
//region constructors | |
public MaterialErrorTextView(Context context, AttributeSet attrs, int defStyle) { | |
super(context, attrs, defStyle); | |
init(attrs); | |
} | |
public MaterialErrorTextView(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
init(attrs); | |
} | |
public MaterialErrorTextView(Context context) { | |
super(context); | |
init(null); | |
} | |
//endregion | |
private int maxHeight; | |
private CharSequence lastValue; | |
private CharSequence newValue; | |
@Override | |
public void setText(CharSequence text, BufferType type) { | |
super.setText(text, type); | |
lastValue = newValue; | |
newValue = text; | |
startAnimationIfNeeded(); | |
} | |
private void startAnimationIfNeeded() { | |
ObjectAnimator animator = null; | |
if ((lastValue == null || lastValue.equals("")) && !newValue.equals("")) { | |
animator = getToMaxAnimator(); | |
} else if ((lastValue != null && !lastValue.equals("")) && newValue.equals("")) { | |
animator = getToMinAnimator(); | |
} | |
if (animator != null) { | |
animator.addUpdateListener(this); | |
animator.start(); | |
} | |
} | |
@Override | |
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { | |
super.onMeasure(widthMeasureSpec, heightMeasureSpec); | |
} | |
@Override | |
protected void onSizeChanged(int w, int h, int oldw, int oldh) { | |
super.onSizeChanged(w, h, oldw, oldh); | |
if (maxHeight < h) { | |
maxHeight = h; | |
} | |
} | |
private ObjectAnimator getToMaxAnimator() { | |
return ObjectAnimator.ofInt(this, "height", 0, maxHeight); | |
} | |
private ObjectAnimator getToMinAnimator() { | |
return ObjectAnimator.ofInt(this, "height", maxHeight, 0); | |
} | |
@Override | |
public void onAnimationUpdate(ValueAnimator animation) { | |
invalidate(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment