Home > Java > javaTutorial > How to Prevent Infinite Loop When Clearing EditText Fields on Text Change?

How to Prevent Infinite Loop When Clearing EditText Fields on Text Change?

Barbara Streisand
Release: 2024-11-20 12:19:09
Original
284 people have browsed it

How to Prevent Infinite Loop When Clearing EditText Fields on Text Change?

android on Text Change Listener

This question seeks a solution to prevent an infinite loop when applying a Text Change Listener to two EditText fields, field1 and field2. Upon a text change in field1, field2 should be cleared, and vice versa.

The initial implementation involved attaching TextWatchers to both fields, where upon text change in field1, field2 would be cleared, and vice versa. However, this resulted in a crash due to the fields attempting to change each other indefinitely.

Solution:

To prevent the infinite loop, a check can be added to the TextWatchers to only clear the other field when its text is not empty (i.e., when the length is different than 0).

Here's an updated implementation:

field1.addTextChangedListener(new TextWatcher() {

   @Override
   public void afterTextChanged(Editable s) {}

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

   @Override    
   public void onTextChanged(CharSequence s, int start,
     int before, int count) {
      if(s.length() != 0)
        field2.setText("");
   }
  });

field2.addTextChangedListener(new TextWatcher() {

   @Override
   public void afterTextChanged(Editable s) {}

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

   @Override
   public void onTextChanged(CharSequence s, int start,
     int before, int count) {
      if(s.length() != 0)
         field1.setText("");
   }
  });
Copy after login

This approach ensures that when field1 changes and has text, it clears field2. Similarly, field2 only clears field1 when its text is not empty. Thus, the infinite loop is avoided while achieving the desired behavior.

The above is the detailed content of How to Prevent Infinite Loop When Clearing EditText Fields on Text Change?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template