Изменение цвета подчеркивания EditText с анимацией заполнения, как в формах Google.
Шаг 1:
В Android Studio создайте новый проект с Empty Activity.
Шаг 2:
В build.gradle добавьте зависимость для библиотеки поддержки дизайна Android (она будет использоваться только для плавающих меток), и ваш minSdkVersion должен быть равен 13. Это должно выглядеть примерно так:
apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.2" ... } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.0.1' compile 'com.android.support:design:23.0.1' }
Шаг 3:
Теперь откройте файл макетаactivity_main.xml и добавьте макет, как показано ниже. В этом макете, как вы можете видеть, я установил фон EditText прозрачным и использовал FrameLayout с двумя представлениями вместо значения по умолчанию. нижняя строка для EditText. Мы будем использовать второй Viewвнутри FrameLayout, который сначала будет невидимым и в фокусе, он заполнит ширину анимацией.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="16dp" android:paddingLeft="16dp" android:paddingRight="16dp" android:paddingTop="16dp"> <LinearLayout android:id="@+id/username" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="bottom" android:orientation="horizontal"> <ImageView android:id="@+id/icon_username" android:layout_width="30dp" android:layout_height="30dp" android:layout_marginRight="10dp" android:src="@drawable/ic_username" /> <android.support.design.widget.TextInputLayout android:id="@+id/username_layout" android:layout_width="match_parent" android:layout_height="45dp" android:gravity="bottom"> <EditText android:id="@+id/edt_username" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#00000000" android:hint="Username" android:inputType="textEmailAddress" android:singleLine="true" android:textSize="18sp" /> </android.support.design.widget.TextInputLayout> </LinearLayout> <FrameLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="3dp" android:layout_marginRight="3dp" android:layout_marginTop="5dp"> <View android:id="@+id/view_username" android:layout_width="wrap_content" android:layout_height="2dp" android:background="#aaaaaa" /> <View android:id="@+id/second_view_username" android:layout_width="match_parent" android:layout_height="2dp" android:background="#E74C3C" android:visibility="invisible" /> </FrameLayout> <LinearLayout android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:gravity="bottom" android:orientation="horizontal"> <ImageView android:id="@+id/icon_password" android:layout_width="30dp" android:layout_height="30dp" android:layout_marginRight="10dp" android:src="@drawable/ic_password" /> <android.support.design.widget.TextInputLayout android:id="@+id/password_layout" android:layout_width="match_parent" android:layout_height="45dp" android:gravity="bottom"> <EditText android:id="@+id/edt_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#00000000" android:hint="Password" android:inputType="textEmailAddress" android:singleLine="true" android:textSize="18sp" /> </android.support.design.widget.TextInputLayout> </LinearLayout> <FrameLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="3dp" android:layout_marginRight="3dp" android:layout_marginTop="5dp"> <View android:id="@+id/view_password" android:layout_width="wrap_content" android:layout_height="2dp" android:background="#aaaaaa" /> <View android:id="@+id/second_view_password" android:layout_width="match_parent" android:layout_height="2dp" android:background="#E74C3C" android:visibility="invisible" /> </FrameLayout> </LinearLayout>
Шаг 4:
Создайте каталог anim в папке res и добавьте в него масштабную анимацию, как показано ниже. Анимация начинается с XScale: 0 и заканчивается в XScale: 1 с поворотом, установленным на 50 %, что означает, что вид, к которому применяется эта анимация, будет заполнять максимальную ширину, начиная с центра.
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <scale android:duration="300" android:fromXScale="0.0" android:fromYScale="1.0" android:toYScale="1.0" android:pivotX="50%" android:toXScale="1.0" /> </set>
Шаг 5:
В свой MainActivity.java добавьте приведенный ниже код. Чтобы получить анимацию, я установил OnFocusChangeListener на EditText. Когда он получает фокус, я изменяю видимость второго View (которое находится поверх первого View в FrameLayout) на Отображается и применяется анимация масштабирования, указанная в файле scale.xml, к представлению. Когда он теряет фокус, второй View снова становится невидимым. Вот как мы изменили бы цвет строки EditText с анимацией.
/* change EditText line color with animation */ package com.githubtech.edittext.edittext; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.EditText; public class MainActivity extends AppCompatActivity { View view_password; View view_username; Animation anim; EditText edt_password; EditText edt_username; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); anim = AnimationUtils.loadAnimation(MainActivity.this, R.anim.scale); view_password = (View) findViewById(R.id.second_view_password); view_username = (View) findViewById(R.id.second_view_username); edt_password = (EditText) findViewById(R.id.edt_password); edt_username = (EditText) findViewById(R.id.edt_username); edt_password.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { view_password.setVisibility(View.VISIBLE); view_password.startAnimation(anim); } else { view_password.setVisibility(View.GONE); } } }); edt_username.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { view_username.setVisibility(View.VISIBLE); view_username.startAnimation(anim); } else { view_username.setVisibility(View.GONE); } } }); } }
Вот и все, наконец-то можно запустить свой проект и увидеть результат.
Полный код: https://github.com/qandeelabbassi/EditText-Line-Animation