一、创建drawable文件
Android中,我们可以通过创建drawable文件来实现对EditText下划线颜色的设置。在res目录下,新建一个drawable文件夹,然后新建一个xml文件my_edittext.xml,代码如下:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <stroke android:width="1dp" //下划线宽度为1dp android:color="#FF0000" //下划线颜色为红色 /> </shape>
在这里,我们定义了一个shape,也就是形状,通过stroke标签表示下划线,设置了下划线的宽度和颜色。
二、在EditText中引用drawable
在我们定义好的drawable文件中,我们可以为EditText设置下划线的颜色。在xml文件中我们需要使用android:background=”@drawable/my_edittext”属性,代码如下:
<EditText android:id="@+id/edittext" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/my_edittext" />
这样就可以将my_edittext.xml中定义的下划线样式应用到EditText中了。
三、通过代码动态修改下划线颜色
有时候我们需要在代码中动态修改EditText的下划线颜色,这时我们可以通过代码来实现。我们可以通过获取EditText的背景Drawable,然后将其转化为GradientDrawable,最后设置下划线颜色即可。代码如下:
EditText editText = findViewById(R.id.edittext); Drawable background = editText.getBackground(); if (background instanceof GradientDrawable) { ((GradientDrawable) background.mutate()).setStroke(1, R.color.blue); }
通过判断获取到的背景Drawable是否是GradientDrawable,然后使用mutate()方法拷贝一个新的Drawable,最后通过setStroke()方法设置下划线颜色。
四、完整的代码示例
my_edittext.xml文件代码:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <stroke android:width="1dp" android:color="#FF0000" /> </shape>
布局文件代码:
<EditText android:id="@+id/edittext" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/my_edittext" />
动态修改下划线颜色代码:
EditText editText = findViewById(R.id.edittext); Drawable background = editText.getBackground(); if (background instanceof GradientDrawable) { ((GradientDrawable) background.mutate()).setStroke(1, R.color.blue); }
至此,我们就完成了对EditText下划线颜色设置的介绍。通过创建drawable文件,设置下划线的颜色,引用到EditText中,就可以实现下划线颜色的定制。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/308294.html