【问题标题】:How to change the color of a particular string in edit text on the fly??-Android如何动态更改编辑文本中特定字符串的颜色??-Android
【发布时间】:2014-05-10 01:16:49
【问题描述】:

在我的应用程序中,我希望用户通过编辑文本以文本形式给出答案。因此,对于正确答案,我希望字母在打字时即时变为绿色(或红色表示不正确)。

例如,如果答案是 DOG,如果用户动态键入 DOG,我希望文本变为绿色。即使他输入的第一个字母是 D,我也希望文本颜色为绿色。只有当用户的输入文本不正确时,我才希望它是红色的。文本颜色应在键入时即时更改。

【问题讨论】:

标签: android user-interface android-activity android-edittext textcolor


【解决方案1】:

创建EditText 并调用addTextChangedListener 为其提供自定义TextWatcher,您最需要覆盖它的onTextChanged

在此方法中,根据您的逻辑更改文本颜色。

快照:

    mEditBox = (EditText) findViewById(R.id.my_edit_box_id);
    mEditBox.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
            int count) {

            String currentText = mEditBox.getText().toString();
            // highligt correct answer in green
            if ("DOG".startsWith(currentText)) { // user starts typing "DOG"
                mEditBox.setTextColor(Color.GREEN);
            } else {
                mEditBox.setTextColor(Color.RED); // incorrect input
            }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

【讨论】:

  • 现在当我运行应用程序时,在第一个实例中,只有当我删除它并再次输入时,答案“DOG”的文本颜色才会变为红色。所以你能帮我一个忙吗?在第一个实例本身更改文本颜色的解决方案?
  • 你的意思是你的编辑框最初包含“默认”文本 DOG 吗?
  • 不。当我第一次输入 DOG 时,文本颜色为红色。只有当我删除它并再次输入时它才会变成绿色。
  • 很奇怪,对我来说很好用。你什么时候打电话给addTextChangedListener?你能不能在onTextChanged 中设置一个断点,看看它是在你开始输入时触发的吗?
猜你喜欢
  • 2020-01-10
  • 2023-03-31
  • 2014-09-28
  • 2013-04-17
  • 2015-08-15
  • 2011-06-05
  • 1970-01-01
  • 2017-03-27
  • 1970-01-01
相关资源
最近更新 更多