问题描述:

I found various answers on how to change the line color of an EditText in Android programatically.

Right now I'm using this solution:

 final Drawable originalDrawable = editText.getBackground();

final Drawable wrappedDrawable = DrawableCompat.wrap(originalDrawable);

DrawableCompat.setTintList(wrappedDrawable, ColorStateList.valueOf(darkVibrantColor));

editText.setBackground(wrappedDrawable);

This does in fact change to color of an EditText, but unfortunately it does not only change the line color of the specific EditText I'm using but the line color of all EditTexts used in my application. Event if they are in different activities.

How do I change the line color of just one specific EditText without changing the line color globally? Thanks.

Update: I cannot use a predefined style as the color is generated dynamically while the application is running.

网友答案:

Try this, could help you

In your style.xml

<style name="MyEditText" parent="Theme.AppCompat.Light">  
    <item name="colorControlNormal">@color/indigo</item>
    <item name="colorControlActivated">@color/pink</item>
    <item name="android:padding">20dp</item>
    <item name="android:textSize">16dp>
    <item name="android:editTextColor">@color/black</item>
    <item name="android:tint">@color/colorPrimary</item>
</style>  

in you edittext add your style

<EditText  
    style="@style/MyEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Subject"/>
网友答案:

I have provided code to programmatically change underline color of EditText.

EditText editTextOne=(EditText) findViewById(R.id.edit_text_one);
Drawable drawable=editTextOne.getBackground();
int color=Color.parseColor("#FFFFFF");
drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
if (Build.VERSION.SDK_INT > 16) {
    editTextOne.setBackground(drawable);
} else {
    editTextOne.setCompoundDrawables(null,null,drawable,null);
}
网友答案:

I found the solution. It's posted in this (not accepted) answer. The trick is to mutate the background drawable after it is retrieved from the EditText.

Here's my working code:

final Drawable originalDrawable = editText.getBackground();
originalDrawable.mutate();
final Drawable wrappedDrawable = DrawableCompat.wrap(originalDrawable);
DrawableCompat.setTintList(wrappedDrawable, ColorStateList.valueOf(darkVibrantColor));
editText.setBackground(wrappedDrawable);
相关阅读:
Top