Blog para desarrollo de aplicaciones en Android, aprende paso a paso como crear aplicaciones.

Usamos cookies propias y de terceros que entre otras cosas recogen datos sobre sus hábitos de navegación para mostrarle publicidad personalizada y realizar análisis de uso de nuestro sitio.
Si continúa navegando consideramos que acepta su uso. OK Más información | Y más

🛠️ Cómo Crear un TextInputLayout en Android: Guía Completa

Cómo Crear un TextInputLayout en Android: Guía Completa
Cómo Crear un TextInputLayout en Android: Guía Completa

Hola amigos 👋 Bienvenidos a un nuevo tutorial de Universo Android. Hoy aprenderemos a crear un TextInputLayout en Android, uno de los componentes más profesionales y elegantes de Material Design para capturar información del usuario.

Al finalizar este tutorial tendrás una aplicación que incluirá:

  • TextInputLayout con diseño Material Design
  • Validación de campos en tiempo real
  • Mensajes de error personalizados
  • Iconos y hints flotantes
  • Contadores de caracteres
  • Diferentes tipos de entrada (email, contraseña, teléfono)

🟩 1. ¿Qué es TextInputLayout?

TextInputLayout es un contenedor de Material Design que envuelve un EditText y proporciona funcionalidades avanzadas como hints animados, mensajes de error, contadores de caracteres y validación visual del estado del campo.

🟩 2. Crear el Proyecto en Android Studio

Creamos un nuevo proyecto en Android Studio con Empty Activity.

🟩 3. Agregar la Dependencia de Material Design

Abre el archivo build.gradle (Module: app) y agrega:

dependencies {
    implementation 'com.google.android.material:material:1.9.0'
}

Sincroniza el proyecto después de agregar la dependencia.

🟩 4. Diseño XML con TextInputLayout

Crea un archivo llamado:

📄 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp"
    android:orientation="vertical">

    <!-- TextInputLayout para Email -->
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/tilEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Correo electrónico"
        app:startIconDrawable="@android:drawable/ic_dialog_email"
        app:endIconMode="clear_text"
        app:helperText="Ingresa un email válido"
        app:helperTextEnabled="true"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/txtEmail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textEmailAddress" />

    </com.google.android.material.textfield.TextInputLayout>

    <!-- TextInputLayout para Contraseña -->
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/tilPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:hint="Contraseña"
        app:startIconDrawable="@android:drawable/ic_lock_idle_lock"
        app:endIconMode="password_toggle"
        app:counterEnabled="true"
        app:counterMaxLength="20"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/txtPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:maxLength="20" />

    </com.google.android.material.textfield.TextInputLayout>

    <!-- TextInputLayout para Nombre -->
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/tilName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:hint="Nombre completo"
        app:startIconDrawable="@android:drawable/ic_menu_myplaces"
        app:endIconMode="clear_text"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/txtName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName" />

    </com.google.android.material.textfield.TextInputLayout>

    <!-- TextInputLayout para Teléfono -->
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/tilPhone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:hint="Teléfono"
        app:startIconDrawable="@android:drawable/stat_sys_phone_call"
        app:prefixText="+504 "
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/txtPhone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="phone" />

    </com.google.android.material.textfield.TextInputLayout>

    <Button
        android:id="@+id/btnValidate"
        android:text="Validar Formulario"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp" />

</LinearLayout>

🟩 5. Lógica Java con Validación

📄 MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.material.textfield.TextInputLayout;
import com.google.android.material.textfield.TextInputEditText;

public class MainActivity extends AppCompatActivity {

    TextInputLayout tilEmail, tilPassword, tilName, tilPhone;
    TextInputEditText txtEmail, txtPassword, txtName, txtPhone;
    Button btnValidate;

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

        // Inicializar TextInputLayouts
        tilEmail = findViewById(R.id.tilEmail);
        tilPassword = findViewById(R.id.tilPassword);
        tilName = findViewById(R.id.tilName);
        tilPhone = findViewById(R.id.tilPhone);

        // Inicializar EditTexts
        txtEmail = findViewById(R.id.txtEmail);
        txtPassword = findViewById(R.id.txtPassword);
        txtName = findViewById(R.id.txtName);
        txtPhone = findViewById(R.id.txtPhone);

        btnValidate = findViewById(R.id.btnValidate);

        btnValidate.setOnClickListener(v -> validateForm());
    }

    private void validateForm() {
        // Resetear errores
        tilEmail.setError(null);
        tilPassword.setError(null);
        tilName.setError(null);
        tilPhone.setError(null);

        boolean isValid = true;

        // Validar Email
        String email = txtEmail.getText().toString().trim();
        if (email.isEmpty()) {
            tilEmail.setError("El email es obligatorio");
            isValid = false;
        } else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            tilEmail.setError("Email inválido");
            isValid = false;
        }

        // Validar Contraseña
        String password = txtPassword.getText().toString();
        if (password.isEmpty()) {
            tilPassword.setError("La contraseña es obligatoria");
            isValid = false;
        } else if (password.length() < 6) {
            tilPassword.setError("Mínimo 6 caracteres");
            isValid = false;
        }

        // Validar Nombre
        String name = txtName.getText().toString().trim();
        if (name.isEmpty()) {
            tilName.setError("El nombre es obligatorio");
            isValid = false;
        }

        // Validar Teléfono
        String phone = txtPhone.getText().toString().trim();
        if (phone.isEmpty()) {
            tilPhone.setError("El teléfono es obligatorio");
            isValid = false;
        } else if (phone.length() < 8) {
            tilPhone.setError("Teléfono inválido");
            isValid = false;
        }

        if (isValid) {
            Toast.makeText(this, "✅ Formulario válido", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "❌ Corrige los errores", Toast.LENGTH_SHORT).show();
        }
    }
}

🟩 6. Propiedades Importantes de TextInputLayout

PropiedadDescripción
app:startIconDrawableIcono al inicio del campo
app:endIconModeModo del icono final (clear_text, password_toggle, etc.)
app:helperTextTexto de ayuda debajo del campo
app:counterEnabledHabilita contador de caracteres
app:counterMaxLengthLongitud máxima para el contador
app:prefixTextTexto prefijo (ej: +504)
app:suffixTextTexto sufijo
app:errorEnabledHabilita mensajes de error

🟩 7. Estilos de TextInputLayout

Material Design ofrece tres estilos principales:

<!-- Estilo Outlined (Contorno) -->
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"

<!-- Estilo Filled (Relleno) -->
style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox"

<!-- Estilo Dense (Compacto) -->
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"

▶️ Cómo Ejecutar tu Aplicación

  1. Abre Android Studio
  2. Presiona Run para ejecutar el proyecto
  3. Si no tienes un emulador, crea uno desde AVD Manager
  4. Verás tus TextInputLayouts funcionando con validación y animaciones

🧪 Resultado Final

Tu aplicación mostrará campos de entrada profesionales con:

  • Hints flotantes animados
  • Iconos personalizados
  • Validación en tiempo real
  • Mensajes de error claros
  • Contador de caracteres
  • Toggle para mostrar/ocultar contraseña

📥 Descargar Proyecto de Ejemplo

Puedes descargar el proyecto completo desde el siguiente enlace:

👉   

🙌 Gracias por Visitar mi Blog

Si este tutorial te fue útil:

✔️ Compártelo
✔️ Déjame un comentario
✔️ Sígueme para más contenido sobre Android y programación

¡Estoy aquí para ayudarte!

❓ Preguntas Frecuentes (FAQ)

1. ¿Qué diferencia hay entre EditText y TextInputLayout?
TextInputLayout es un contenedor que envuelve EditText y agrega funcionalidades de Material Design como hints flotantes, errores, iconos y contadores.

2. ¿Puedo cambiar el color del TextInputLayout?
Sí, puedes personalizar colores en styles.xml usando boxStrokeColor, hintTextColor y errorTextColor.

3. ¿Es compatible con versiones antiguas de Android?
Sí, Material Components es compatible desde Android API 14 (Android 4.0) en adelante.

4. ¿Cómo valido campos en tiempo real?
Puedes usar TextWatcher en el EditText para validar mientras el usuario escribe.

No hay comentarios:

Publicar un comentario