【问题标题】:How to call TextWatcher from Class如何从类中调用 TextWatcher
【发布时间】:2016-08-25 10:42:57
【问题描述】:

我在EditText 字段上有提示文本和普通文本,我为两者指定了不同的Font-SizeFont-ColorFont-Name。我已经把它放在我的 ActivityClass 中,它工作正常。我有大约10 Edit Text 字段,所以如果我为所有人添加Textwatcher,并且一次又一次地做同样的事情,那将是非常奇怪的。所以我决定创建一个类并将TextWatcher 放在那里。

但添加后,它停止工作。它不会改变文字颜色,请通过class指导我如何实现这一点

public class FormTextCosmetics {

 public void changeHintText(final EditText editText){

        hintFontColor= context.getResources().getColor(R.color.white);
        normalFontColor= context.getResources().getColor(R.color.grayCheckoutFont);


        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

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

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length() > 0){
                    editText.setTextSize(normalTextSize);
                    editText.setTypeface(Typeface.create(normalFontFamily, Typeface.NORMAL));
                    editText.setTextColor(normalFontColor);
                    editText.setAlpha(1);
                }else{
                    editText.setTextSize(hintFontSize);
                    editText.setTypeface(Typeface.create(hintFontFamily, Typeface.NORMAL));
                    editText.setTextColor(hintFontColor);
                    editText.setAlpha(0.52f);
                }
            }
        });

    }

主要活动类

FormTextCosmetics formTextCosmetics= new FormTextCosmetics(this);
formTextCosmetics.changeHintText(etName);

我也尝试将上述代码放在另一个Textwatcher 中,但它也不影响文本。

【问题讨论】:

    标签: android android-layout android-fragments android-edittext textwatcher


    【解决方案1】:

    您的editText 没有“意识到”它应该在您的课程发生变化时调用您的课程。
    你应该这样做——你的班级应该实现TextWatcher

    public class FormTextCosmetics implements TextWatcher {
        //Your code goes here
    }
    

    然后你像这样使用它 -

    etName.addTextChangedListener(new FormTextCosmetics());
    

    现在editText 将在其文本中发生任何事情时调用您的类。

    【讨论】:

      猜你喜欢
      • 2012-01-22
      • 2023-03-24
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多