Android Implementation EditText Adding Underline

  • 2021-10-13 08:43:16
  • OfStack

In Android high version, there is an underline by default, and the color of the underline by default is controlled by its theme color!

Controls are as follows:


 <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    **<item name="colorAccent">@color/colorPrimaryDark</item>**

Therefore, you only need to modify the color of colorAccent, and the color of its underscore can be modified!

In the lower version and the higher version, it is also possible to add underscores! There are two methods:

Method 1:


// You must set its background to empty at this time 
<EditText
    android:background="@null"
    android:drawableBottom="@drawable/line"
    android:hint=" Please enter your mobile phone number "
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

// The resource name is  drawable/line
<shape xmlns:android="http://schemas.android.com/apk/res/android">
  <solid android:color="@color/colorBlue" />
  <size
    android:height="1dp"
    android:width="1000dp" />
</shape>

Method 2: By customizing editText


public class UnderLineEditText extends EditText {
  private Paint paint;

  public UnderLineEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    // Set the properties of the brush 
    paint = new Paint();
    paint.setStyle(Paint.Style.STROKE);
    // Set the brush color to red 
    paint.setColor(Color.RED);
  }

  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    /**canvas Draw a straight line from the lower left corner to the lower right corner. this.getHeight()-2 Is to get the parent edittext The height, but it must be -2 Only in this way can we ensure that 
     *  The horizontal line drawn is in edittext Above, it coincides with the original underline 
     */
    canvas.drawLine(0, this.getHeight()-2, this.getWidth()-2, this.getHeight()-2, paint);
  }
}

Here are a few points to note:

Its 1: can also inherit android. support. v7.widget. AppCompatEditText, but sometimes the focus can not be obtained

Second, the position of the underscore is determined


Related articles: