简体   繁体   中英

Change EditText background color and keep underline

The line underneath the text is a drawable set to the background of the view and when editText.setBackgroundColor(color) is called the following happens internally:

setBackground(new ColorDrawable(color));

This removes the drawable that contained the line and replaces it with the color we gave it.

Is it possible to change the background color of an EditText without having the line under the text disappear?

Setting the EditText inside a layout and changing the layout's background color is not an option.

Try to make drawable some think like this:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="-2dp" android:left="-2dp" android:right="-2dp">
        <shape> 
            <solid android:color="@color/background_color"/>
            <stroke android:color="@color/underline_color" android:width="2dp"/>
        </shape>
    </item>
</layer-list>

The set your EditText background from resources like this:

editText.setBackgroundResource(R.drawable.name_to_xml_file);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM