简体   繁体   中英

How do I change background color of EditText fields by comparing values?

I'm making a small app on android studio and I have different EditText fields that I want to change the background to 3 colors depending on the value inside. 1 for if value is equal to goal and 1 for less than goal and last one for more (<,=,>). I already set up colors in the style category but I have no idea how to make the code on the main.java so that it recognizes the EditText fields and change the color according to the value given when compared to the goal.

Text Watcher

editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // TODO Auto-generated method stub
    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
    }
});

However you want to use this. You can do it as the user is type in their message, or if they click a button, etc.

To use it, you can do something like this... (in side the method)

if(s.equals("1")){
    editText.setBackgroundResource(getResources().getColor(R.color.blue));
}

First, use findViewById to get a reference to the EditText field you want to compare, and assign it to a variable:

EditText enteredValueEditText = findViewById(R.id.entered_value_edittext);

Next, retrieve the value from the EditText field:

String value = enteredValueEditText.getText().toString().trim();

Convert to an integer:

int valueInt = Integer.parseInt(value);

Then, compare it to your goal value and set the background color appropriately using the setBackgroundColor command:

if (goal > valueInt) {    
  enteredValue.setBackgroundColor(getResources().getColor(R.color.green));
} else if (goal < valueInt) {
    enteredValue.setBackgroundColor(getResources().getColor(R.color.red));
} else if (goal == valueInt) {
 enteredValue.setBackgroundColor(getResources().getColor(R.color.blue));
}

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