一、創建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/zh-tw/n/308294.html
微信掃一掃
支付寶掃一掃