TextInputLayout,EditText提示动画,隐藏提示

时间:2015-08-28 09:05:36

标签: android android-edittext android-textinputlayout

我的EditText包含在TextInputLayout中。在第一个EditText中输入文本后,当焦点移动到另一个输入字段时,我想让前一个EditText的提示消失。

我怎样才能实现这个目标?

1 个答案:

答案 0 :(得分:0)

我想你想要的是,如果焦点从第一个输入字段变为第二个输入字段,那么第一个输入字段的提示应该消失。下面是执行相同操作的代码。

<强> activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true">

<android.support.design.widget.TextInputLayout
    android:id="@+id/first_text_input_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="hello">

    <EditText
        android:id="@+id/first_edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/first_text_input_layout">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="hello" />
</android.support.design.widget.TextInputLayout>
</RelativeLayout>

<强> MainActivity.java

package com.example.gaurav.myapplication;

import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;


public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final TextInputLayout textInputLayout = (TextInputLayout) findViewById(R.id.first_text_input_layout);
    EditText editText = (EditText) findViewById(R.id.first_edit_text);

    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
             //Below code will check if editext has focus then show hint 

             //else if it dosen't have focus and user has entered some value only then hide hint.
            if (hasFocus){
                textInputLayout.setHint("hello");
            } else if ( !TextUtils.isEmpty(editText.getText().toString().trim())){
                textInputLayout.setHint("");

            }
        }
    });
}
}