ในบางสถานการณ์ เราต้องการเปลี่ยนสีเส้นใต้ (Bottom Line) ของ EditText ให้เข้ากับสีพื้นหลังหรือธีมของแอป ตัวอย่างนี้แสดงวิธีการทำอย่างง่ายด้วย android:backgroundTint
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio ไปที่ File → New Project
ขั้นตอนที่ 2: เพิ่ม Layout XML
เพิ่มโค้ดใน res/layout/activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/parent"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:gravity="center"
android:orientation="vertical">
<EditText
android:id="@+id/editText"
android:hint="Bottom line color change"
android:layout_width="wrap_content"
android:backgroundTint="@android:color/holo_green_light"
android:layout_height="wrap_content" />
</LinearLayout>
โค้ดสำคัญคือ:
android:backgroundTint="@android:color/holo_green_light"
สามารถเปลี่ยนสีได้ตามต้องการ เช่น @color/colorPrimary, #FF0000, หรือ @android:color/holo_blue_dark
ขั้นตอนที่ 3: เพิ่มโค้ด Java
เพิ่มโค้ดใน src/MainActivity.java:
package com.example.andy.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
int view = R.layout.activity_main;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
}
}
วิธีอื่นๆ ในการปรับแต่ง EditText:
- TextInputLayout (Material Design) - ใช้
app:boxStrokeColorและapp:boxStrokeErrorColorสำหรับ Material Components - Custom Drawable - สร้าง
shapeXML สำหรับ background แล้วตั้งค่าandroid:background - Programmatically -
editText.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN))
ตัวอย่าง TextInputLayout (แนะนำสำหรับ Material Design)
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:boxStrokeColor="@color/colorPrimary"
app:boxStrokeErrorColor="@color/colorError"
app:hintTextColor="@color/colorPrimary">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email" />
</com.google.android.material.textfield.TextInputLayout>
การทดสอบ
รันแอปพลิเคชัน จะเห็น EditText มีเส้นใต้สีเขียว

ในผลลัพธ์ แสดงการเปลี่ยนสีเส้นใต้ของ EditText