Guide to Adding an Underline to EditText in Android Studio

Guide to Adding an Underline to EditText in Android Studio

Are you working on an Android application and want to add an underline to your EditText? This article will help you explore several methods to achieve this – using XML Attributes, code, and Text Appearance. Let's dive in!

Method 1: Using XML Attributes

The first method involves creating a drawable resource that simulates an underline and setting it as the background of the EditText. Here is how you can do it:

Step 1: Create a Drawable Resource

1.1. Create a new drawable XML file in your project's res/drawable directory. For instance, name it underline_edittext.xml.

?xml version"1.0" encoding"utf-8"? shape xmlns:android"" android:shape"rectangle"> size android:height"1dp"/> solid android:color"@android:color/darker_gray"/> /shape

Step 2: Set the Drawable as the Background

Add the following attributes to your EditText in your layout XML file:

EditText android:id"@ id/editText" android:layout_width"match_parent" android:layout_height"wrap_content" android:background"@drawable/underline_edittext" android:padding"10dp" android:cursorVisible"true" /EditText

Method 2: Using Code

If you prefer to set the underline programmatically, you can use code in your activity or fragment:

EditText editText findViewById(); (editText, (this, R.drawable.underline_edittext));

Method 3: Using Text Appearance

If you want to underline the text itself rather than just the input field, you can use Text Appearance:

Using XML

EditText android:id"@ id/editText" android:layout_width"match_parent" android:layout_height"wrap_content" android:paintFlags" Paint.UNDERLINE_TEXT_FLAG " /EditText

Using Java

EditText editText findViewById(); (Paint.UNDERLINE_TEXT_FLAG);

Summary

Conclusion: Choose the method that best suits your design needs. Method 1 is ideal for a simple and commonly used underline effect for input fields. Method 2 is useful if you want more control over the visual appearance through code. Method 3 is perfect for underlining the text itself, rather than just the field.

Further Customization

You can further customize the underline by adjusting the drawable or using different attributes in the Text Appearance. Experimenting with different styles can help you match the design of your application seamlessly.