簡體   English   中英

如何通過比較值更改EditText字段的背景顏色?

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

我正在android studio上做一個小應用程序,我有不同的EditText字段,我想根據內部值將背景更改為3種顏色。 如果值等於目標,則為1;如果目標小於目標,則為1;如果大於等於(<,=,>),則最后一個。 我已經在樣式類別中設置了顏色,但是我不知道如何在main.java上編寫代碼,以便它可以識別EditText字段並根據與目標相比給出的值更改顏色。

文字觀察器

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
    }
});

但是,您想使用它。 您可以在用戶輸入其消息時,或者在他們單擊按鈕等時進行操作。

要使用它,您可以執行以下操作(在方法旁邊)

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

首先,使用findViewById獲取對要比較的EditText字段的引用,並將其分配給變量:

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

接下來,從EditText字段中檢索值:

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

轉換為整數:

int valueInt = Integer.parseInt(value);

然后,將其與目標值進行比較,並使用setBackgroundColor命令適當設置背景色:

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));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM