Android TextWatcher对象。Java匿名类是如何工作的?

3
private TextWatcher billEditTextWatcher = new TextWatcher() 
   {
      // called when the user enters a number
      @Override
      public void onTextChanged(CharSequence s, int start, 
         int before, int count) 
      {         
         // convert billEditText's text to a double
         try
         {
            currentBillTotal = Double.parseDouble(s.toString());
         } // end try
         catch (NumberFormatException e)
         {
            currentBillTotal = 0.0; // default if an exception occurs
         } // end catch 

         // update the standard and custom tip EditTexts
         updateStandard(); // update the 10, 15 and 20% EditTexts
         updateCustom(); // update the custom tip EditTexts
      } // end method onTextChanged

      @Override
      public void afterTextChanged(Editable s) 
      {
      } // end method afterTextChanged

      @Override
      public void beforeTextChanged(CharSequence s, int start, int count,
         int after) 
      {
      } // end method beforeTextChanged
   }; // end billEditTextWatcher

这是一个专业的小费计算器应用程序的代码片段。有人能解释一下这是如何工作的吗?
通常,我只需编写以下内容即可创建一个新对象。
TextWatcher billEditTextWatcher = new TextWatcher();

我知道private的作用是什么,但是在创建新对象时为什么会有方法呢?它基本上是按照字面意思做吗?覆盖TextWatcher类中的原始方法?

希望我的问题表达清楚了,因为我很困惑。

提前感谢!

2个回答

3

请查看Java匿名类的工作原理,它作为一个表达式。希望这有所帮助。 - Haifeng Zhang
感谢blue和haif! - user2927724
抱歉回复了错误的人,我正在使用手机回答。 - Haifeng Zhang

1

正如名称所示,TextWatcher将感知 EditText 的所有事件。

比如当您在可编辑区域中输入内容时。

它具有以下回调(观察状态):

  1. 按键 - beforeTextChanged();
  2. 按下 - afterTextChanged();
  3. 文本更改 - onTextChanged();

所有回调方法都包含由事件生成器传递的相对数据。例如,按下了哪个键,键的Unicode(ASCII)等。

基本上,TextWatcher用于在输入数据时监视EditText或多行EditText。我们可以执行操作并监视输入的字符或在EditText中输入了多少个字符。

技术描述:

  1. 如果要使用 TextWatcher ,则需要使用 TextWather 对象注册您的 EditText

例如:

EditText editTextPassword;  // Some EditText object.

TextWatcher billEditTextWatcher = new TextWatcher();  // TextWather object creation

editTextPassword.addTextChangedListener(billEditTextWatcher );  // EditText registation with Textwather object.
  1. 默认情况下,TextWatcher的所有回调函数都是空的,这就是为什么您需要根据您的要求给出所有回调函数的定义。

    private TextWatcher billEditTextWatcher = new TextWatcher() 
     {
    
      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) 
      {         
    
          // 在onTextChanged中编写代码。
    
      } 
    
      @Override
      public void afterTextChanged(Editable s) 
      {
    
          //在afterTextChanged中编写代码。
    
      } 
    
      @Override
      public void beforeTextChanged(CharSequence s, int start, int count,
         int after) 
      {
    
         //在beforeTextChanged中编写代码。
    
      } 
    }; 
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接