简体   繁体   中英

Android Change Color of EditText Accent via Java When Active & Not Active

I have been using the code below that I got from another question to split into two lines to edit the color programmatically.

Changing tint color of Android EditText programmatically

((EditText) row1.getVirtualChildAt(i))

The below code is what I'm using after the above line to change the color.

.getBackground().mutate().setColorFilter(getResources().getColor(R.color.Green), PorterDuff.Mode.SRC_ATOP);

Right now it sets the underline color so its always green whether or not the EditText box is being used.

How can I set it so it goes back to the default color after I click away from the EditText box. I would also be fine with specifying another color as the default like a light gray color.

You can register your edit text with OnFocusChangeListener.java and on focus change you can change the color.

void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
// color while typing
}else{
// color when clicked away
}

}

You can create color selector xml for different edit text states that you want to add in the res/color/your_edittext_color_state.xml folder.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="#YOUR_COLOR"/>
    <item android:state_focused="true" android:color="#ANY_COLOR"/>
    <item android:color="#DEFAULT_COLOR"/>
</selector>

Then you can set the foregroundTint in your code

editText.setForegroundTintList(getApplicationContext().getResources().getColorStateList(R.color.your_edittext_color_state));

I ended up following the answer that was given here: How do I create ColorStateList programmatically?

I did change a few things around as order DOES matter and it took a moment to realize this.

Placed the below code block right at the beginning of MainActivity.

int[][] states = new int[][] {
        new int[] { android.R.attr.state_focused}, // enabled
        //new int[] {-android.R.attr.state_enabled}, // disabled
        //new int[] {-android.R.attr.state_checked}, // unchecked
        new int[] { android.R.attr.state_window_focused}  // pressed
};

int[] colors = new int[] {
        Color.GREEN,
        //Color.BLUE,
        //Color.YELLOW,
        Color.GRAY
};

ColorStateList myColorAccentList = new ColorStateList(states, colors);

Then placed my statement in my for loop where it was needed.

((EditText) row1.getVirtualChildAt(i)).setBackgroundTintList(myColorAccentList);

For anyone else you will probably just want to add this part at the end of your edittext.

.setBackgroundTintList(myColorAccentList);

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