/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.support.design.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.os.Handler; import android.os.Message; import android.support.design.R; import android.support.v4.view.AccessibilityDelegateCompat; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewPropertyAnimatorListenerAdapter; import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.AttributeSet; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.view.animation.AccelerateInterpolator; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; /** * Layout which wraps an {@link android.widget.EditText} (or descendant) to show a floating label * when the hint is hidden due to the user inputting text. * * Also supports showing an error via {@link #setErrorEnabled(boolean)} and * {@link #setError(CharSequence)}. * *

Please note: this class sets a {@link android.view.View.OnFocusChangeListener} on the wrapped * {@link EditText}. If you need to set your own listener, then you should wrap the existing one * and forward the call like so: *

 * TextInputLayout inputLayout = ...;
 * EditText editText = inputLayout.getEditText();
 * final OnFocusChangeListener existing = editText.getOnFocusChangeListener();
 *
 * editText.setOnFocusChangeListener(new OnFocusChangeListener() {
 *     public void onFocusChange(View view, boolean focused) {
 *         existing.onFocusChange(view, focused);
 *
 *         // Your custom logic
 *     }
 * });
 * 
*

*/ public class TextInputLayout extends LinearLayout { private static final int ANIMATION_DURATION = 200; private static final int MSG_UPDATE_LABEL = 0; private EditText mEditText; private CharSequence mHint; private boolean mErrorEnabled; private TextView mErrorView; private int mErrorTextAppearance; private int mDefaultTextColor; private int mFocusedTextColor; private final CollapsingTextHelper mCollapsingTextHelper; private final Handler mHandler; private ValueAnimatorCompat mAnimator; public TextInputLayout(Context context) { this(context, null); } public TextInputLayout(Context context, AttributeSet attrs) { super(context, attrs); setOrientation(VERTICAL); setWillNotDraw(false); mCollapsingTextHelper = new CollapsingTextHelper(this); mHandler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message message) { switch (message.what) { case MSG_UPDATE_LABEL: updateLabelVisibility(true); return true; } return false; } }); mCollapsingTextHelper.setTextSizeInterpolator(AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR); mCollapsingTextHelper.setPositionInterpolator(new AccelerateInterpolator()); mCollapsingTextHelper.setCollapsedTextGravity(Gravity.TOP); final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TextInputLayout, 0, R.style.Widget_Design_TextInputLayout); mHint = a.getText(R.styleable.TextInputLayout_android_hint); final int hintAppearance = a.getResourceId( R.styleable.TextInputLayout_hintTextAppearance, -1); if (hintAppearance != -1) { mCollapsingTextHelper.setCollapsedTextAppearance(hintAppearance); } mErrorTextAppearance = a.getResourceId(R.styleable.TextInputLayout_errorTextAppearance, 0); final boolean errorEnabled = a.getBoolean(R.styleable.TextInputLayout_errorEnabled, false); mDefaultTextColor = getThemeAttrColor(android.R.attr.textColorHint); mFocusedTextColor = mCollapsingTextHelper.getCollapsedTextColor(); mCollapsingTextHelper.setCollapsedTextColor(mDefaultTextColor); mCollapsingTextHelper.setExpandedTextColor(mDefaultTextColor); a.recycle(); if (errorEnabled) { setErrorEnabled(true); } if (ViewCompat.getImportantForAccessibility(this) == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) { // Make sure we're important for accessibility if we haven't been explicitly not ViewCompat.setImportantForAccessibility(this, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); } ViewCompat.setAccessibilityDelegate(this, new TextInputAccessibilityDelegate()); } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { if (child instanceof EditText) { params = setEditText((EditText) child, params); super.addView(child, 0, params); } else { // Carry on adding the View... super.addView(child, index, params); } } /** * Set the typeface to use for the both the expanded and floating hint. * * @param typeface typeface to use, or {@code null} to use the default. */ public void setTypeface(Typeface typeface) { mCollapsingTextHelper.setTypeface(typeface); } private LayoutParams setEditText(EditText editText, ViewGroup.LayoutParams lp) { // If we already have an EditText, throw an exception if (mEditText != null) { throw new IllegalArgumentException("We already have an EditText, can only have one"); } mEditText = editText; // Use the EditText's typeface, and it's text size for our expanded text mCollapsingTextHelper.setTypeface(mEditText.getTypeface()); mCollapsingTextHelper.setExpandedTextSize(mEditText.getTextSize()); // Add a TextWatcher so that we know when the text input has changed mEditText.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { mHandler.sendEmptyMessage(MSG_UPDATE_LABEL); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }); // Use the EditText's hint colors since the developer may have changed it mDefaultTextColor = mEditText.getHintTextColors().getDefaultColor(); // Add focus listener to the EditText so that we can notify the label that it is activated. // Allows the use of a ColorStateList for the text color on the label mEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean focused) { mHandler.sendEmptyMessage(MSG_UPDATE_LABEL); } }); // If we do not have a valid hint, try and retrieve it from the EditText if (TextUtils.isEmpty(mHint)) { setHint(mEditText.getHint()); // Clear the EditText's hint as we will display it ourselves mEditText.setHint(null); } if (mErrorView != null) { // Add some start/end padding to the error so that it matches the EditText ViewCompat.setPaddingRelative(mErrorView, ViewCompat.getPaddingStart(mEditText), 0, ViewCompat.getPaddingEnd(mEditText), mEditText.getPaddingBottom()); } // Update the label visibility with no animation updateLabelVisibility(false); // Create a new FrameLayout.LayoutParams so that we can add enough top margin // to the EditText so make room for the label LayoutParams newLp = new LayoutParams(lp); Paint paint = new Paint(); paint.setTypeface(mCollapsingTextHelper.getTypeface()); paint.setTextSize(mCollapsingTextHelper.getExpandedTextSize()); newLp.topMargin = (int) -paint.ascent(); return newLp; } private void updateLabelVisibility(boolean animate) { boolean hasText = !TextUtils.isEmpty(mEditText.getText()); boolean isFocused = mEditText.isFocused(); mCollapsingTextHelper.setExpandedTextColor(mDefaultTextColor); mCollapsingTextHelper.setCollapsedTextColor( isFocused ? mFocusedTextColor : mDefaultTextColor); if (hasText || isFocused) { // We should be showing the label so do so if it isn't already collapseHint(animate); } else { // We should not be showing the label so hide it expandHint(animate); } } /** * @return the {@link android.widget.EditText} text input */ public EditText getEditText() { return mEditText; } /** * Set the hint to be displayed in the floating label */ public void setHint(CharSequence hint) { mHint = hint; mCollapsingTextHelper.setText(hint); sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); } /** * Whether the error functionality is enabled or not in this layout. Enabling this * functionality before setting an error message via {@link #setError(CharSequence)}, will mean * that this layout will not change size when an error is displayed. */ public void setErrorEnabled(boolean enabled) { if (mErrorEnabled != enabled) { if (mErrorView != null) { ViewCompat.animate(mErrorView).cancel(); } if (enabled) { mErrorView = new TextView(getContext()); mErrorView.setTextAppearance(getContext(), mErrorTextAppearance); mErrorView.setVisibility(INVISIBLE); addView(mErrorView); if (mEditText != null) { // Add some start/end padding to the error so that it matches the EditText ViewCompat.setPaddingRelative(mErrorView, ViewCompat.getPaddingStart(mEditText), 0, ViewCompat.getPaddingEnd(mEditText), mEditText.getPaddingBottom()); } } else { removeView(mErrorView); mErrorView = null; } mErrorEnabled = enabled; } } /** * Sets an error message that will be displayed below our {@link EditText}. If the * {@code error} is {@code null}, the error message will be cleared. *

* If the error functionality has not been enabled via {@link #setErrorEnabled(boolean)}, then * it will be automatically enabled if {@code error} is not empty. * * @param error Error message to display, or null to clear */ public void setError(CharSequence error) { if (!mErrorEnabled) { if (TextUtils.isEmpty(error)) { // If error isn't enabled, and the error is empty, just return return; } // Else, we'll assume that they want to enable the error functionality setErrorEnabled(true); } if (!TextUtils.isEmpty(error)) { mErrorView.setText(error); mErrorView.setVisibility(VISIBLE); ViewCompat.setAlpha(mErrorView, 0f); ViewCompat.animate(mErrorView) .alpha(1f) .setDuration(ANIMATION_DURATION) .setInterpolator(AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR) .setListener(null) .start(); } else { if (mErrorView.getVisibility() == VISIBLE) { ViewCompat.animate(mErrorView) .alpha(0f) .setDuration(ANIMATION_DURATION) .setInterpolator(AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR) .setListener(new ViewPropertyAnimatorListenerAdapter() { @Override public void onAnimationEnd(View view) { view.setVisibility(INVISIBLE); } }).start(); } } sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); } @Override public void draw(Canvas canvas) { super.draw(canvas); mCollapsingTextHelper.draw(canvas); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (mEditText != null) { final int l = mEditText.getLeft() + mEditText.getCompoundPaddingLeft(); final int r = mEditText.getRight() - mEditText.getCompoundPaddingRight(); mCollapsingTextHelper.setExpandedBounds(l, mEditText.getTop() + mEditText.getCompoundPaddingTop(), r, mEditText.getBottom() - mEditText.getCompoundPaddingBottom()); // Set the collapsed bounds to be the the full height (minus padding) to match the // EditText's editable area mCollapsingTextHelper.setCollapsedBounds(l, getPaddingTop(), r, bottom - top - getPaddingBottom()); mCollapsingTextHelper.recalculate(); } } private void collapseHint(boolean animate) { if (animate) { animateToExpansionFraction(1f); } else { mCollapsingTextHelper.setExpansionFraction(1f); } } private void expandHint(boolean animate) { if (animate) { animateToExpansionFraction(0f); } else { mCollapsingTextHelper.setExpansionFraction(0f); } } private void animateToExpansionFraction(final float target) { if (mAnimator == null) { mAnimator = ViewUtils.createAnimator(); mAnimator.setInterpolator(AnimationUtils.LINEAR_INTERPOLATOR); mAnimator.setDuration(ANIMATION_DURATION); mAnimator.setUpdateListener(new ValueAnimatorCompat.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimatorCompat animator) { mCollapsingTextHelper.setExpansionFraction(animator.getAnimatedFloatValue()); } }); } else if (mAnimator.isRunning()) { mAnimator.cancel(); } mAnimator.setFloatValues(mCollapsingTextHelper.getExpansionFraction(), target); mAnimator.start(); } private int getThemeAttrColor(int attr) { TypedValue tv = new TypedValue(); if (getContext().getTheme().resolveAttribute(attr, tv, true)) { return tv.data; } else { return Color.MAGENTA; } } private class TextInputAccessibilityDelegate extends AccessibilityDelegateCompat { @Override public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { super.onInitializeAccessibilityEvent(host, event); event.setClassName(TextInputLayout.class.getSimpleName()); } @Override public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { super.onPopulateAccessibilityEvent(host, event); final CharSequence text = mCollapsingTextHelper.getText(); if (!TextUtils.isEmpty(text)) { event.getText().add(text); } } @Override public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) { super.onInitializeAccessibilityNodeInfo(host, info); info.setClassName(TextInputLayout.class.getSimpleName()); final CharSequence text = mCollapsingTextHelper.getText(); if (!TextUtils.isEmpty(text)) { info.setText(text); } if (mEditText != null) { info.setLabelFor(mEditText); } final CharSequence error = mErrorView != null ? mErrorView.getText() : null; if (!TextUtils.isEmpty(error)) { info.setContentInvalid(true); info.setError(error); } } } }