AutoCompleteTextView, TextWatcher to EditText

Second pass, deeper: AutoCompleteTextView की adapter + threshold machinery, और TextWatcher के 3 callbacks dissected: हर keystroke से पहले, दौरान और बाद, mobile live search को power करते हुए।

12 min read · 9 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

आप इस Widget से मिल चुके हैं; अब इसकी Machinery से मिलिए

Syllabus आपको वापस एक BCA305-02 acquaintance के पास भेजता है: AutoCompleteTextView और TextWatcher ने FestConnect Mobile-1 बंद किया था। एक revisit एक rerun नहीं है: पिछले साल आपने उन्हें WIRE किया; इस साल आपको machinery explain करने और deeper questions answer करने में सक्षम होना चाहिए।

और आपके पास नया context है: BCA405-01 में आपने keyup और AJAX से web पर live search बनाई। आज का lesson उसी pattern का mobile twin है, और parallel दोनों को master करने का fastest तरीका है।

Theory

AutoCompleteTextView: Recap, Tightened

एक AutoCompleteTextView एक EditText subclass है जो user के typing के साथ filtered suggestions drop down करता है:

  • suggestions एक ArrayAdapter से आते हैं (ListView lesson का middleman फिर से), stock row simple_dropdown_item_1line
  • setThreshold(n): suggestions दिखने से पहले कितने characters चाहिए; default 2 है, और 1 से कम values को 1 treated किया जाता है
  • यह suggest करता है, कभी restrict नहीं करता: free text typeable रहता है, तो सिर्फ़ listed values legal हों तो getText() validate कीजिए

प्रति suggestion एक string = stock adapter; richer dropdown rows = custom adapter: ListView decision rule, verbatim।

Theory

TextWatcher: एक Keystroke के 3 Moments

एक TextWatcher (addTextChangedListener से attached) हर text change को 3 methods के through सुनता है, strict order में:

  • beforeTextChanged(s, start, count, after): OLD text, change से एक instant पहले: s अभी भी "Garb" पढ़ता है
  • onTextChanged(s, start, before, count): NEW text, अभी land हुआ: s "Garba" पढ़ता है: live-search moment
  • afterTextChanged(Editable s): last, और इकलौता जिसे एक Editable मिलता है जिसे आप modify कर सकते हैं

ज़्यादातर real work onTextChanged (react) या afterTextChanged (edit) में रहता है; before old को new से compare करने के लिए है।

Practical

Suggestions AND एक Live Counter वाला Search Box

public class SearchActivity extends AppCompatActivity {
    String[] events = { "Garba Night", "Coding Contest", "Robo Race",
                        "Rangoli", "Quiz Bowl" };

    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_search);

        AutoCompleteTextView box = findViewById(R.id.searchBox);
        box.setAdapter(new ArrayAdapter<>(this,
                android.R.layout.simple_dropdown_item_1line, events));
        box.setThreshold(1);                    // suggest from letter 1

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

            public void onTextChanged(CharSequence s, int start,
                                      int before, int count) {
                int hits = 0;                   // live results counter
                for (String e : events)
                    if (e.toLowerCase().contains(s.toString().toLowerCase()))
                        hits++;
                lblCount.setText(hits + " matching events");
            }

            public void afterTextChanged(Editable s) { }
        });
    }
}

Quiz

Box "Garb" दिखाता है और user a type करता है। किस TextWatcher method में s सबसे पहले "Garba" पढ़ता है, इसे live search के लिए सही hook बनाते हुए?

  1. beforeTextChanged: यह पहले fire होता है, तो इसके पास newest text है
  2. onTextChanged: यह तब fire होता है जब new text land होता है; beforeTextChanged ने अभी भी "Garb" देखा था
  3. afterTextChanged: सिर्फ़ इसे ही new text दिखता है
  4. तीनों को "Garba" मिलता है; सिर्फ़ उनकी timing अलग होती है
Show the answer

onTextChanged: यह तब fire होता है जब new text land होता है; beforeTextChanged ने अभी भी "Garb" देखा था

3 methods एक keystroke को old, new और settled में split करते हैं: beforeTextChanged पहले fire होता है पर pre-change text ("Garb") carry करता है: firing order और text freshness अलग axes हैं, exactly वह confusion जो यह question hunt करता है। onTextChanged नया text land होते ही deliver करता है: live-search hook, वही role play करते हुए जो BCA405-01 के web version में keyup ने play किया। afterTextChanged को भी "Garba" दिखता है (option C का half-truth) पर यह last fire होता है और अपने Editable के through EDITING के लिए exist करता है, first reaction के लिए नहीं।

Think first

Watcher जिसने खुद को हमेशा के लिए Watch किया

एक classmate चाहता है typed text auto-capitalise हो, तो afterTextChanged के अंदर वह capitalised version के साथ s.replace(...) call करता है: और app freeze हो जाता है। Trace कीजिए क्यों, यह इस्तेमाल करते हुए कि एक watcher क्या watch करता है, फिर guard नाम दीजिए।

Show the answer

उसका replace() text को CHANGE करता है: जो एक text change है: जो watcher को फिर fire करता है: जो फिर replace करता है: self-triggered callbacks का एक infinite loop main thread को freeze कर देता है। Guard: edit को conditional बनाइए ताकि पहले से capitalised text untouched रहे (अगर पहला letter पहले से uppercase है, return कीजिए): फिर second pass कुछ नहीं बदलता और cycle मर जाता है। General law: कोई भी watcher जो अपने watch किए हुए को modify करता है idempotent होना चाहिए: इसे अपने own output पर चलाना एक no-op होना चाहिए। यही THE classic TextWatcher exam trap है।

Watch out

Second-Pass Traps (Deeper Set)

सभी 3 Methods Exist होने चाहिए: TextWatcher एक interface है; जो empty छोड़ें उन्हें भी implement कीजिए, वरना compile नहीं होगा।

afterTextChanged के बाहर Edit करना: सिर्फ़ इसका Editable आपके modify करने के लिए है; बाकी 2 के CharSequences read-only views हैं।

Suggestion Validation नहीं है: free text अभी भी एक AutoCompleteTextView में enter हो सकता है; अगर सिर्फ़ list वाली values match करनी हों तो final value list के against check कीजिए।

Per Keystroke Heavy Work: onTextChanged constantly fire होता है; वहाँ slow code typing को lag कराता है: इसे light रखिए।

Theory

एक Pattern, दो Platforms

Twins को side by side रखिए: web live search = keyup event + AJAX + list repaint; mobile = onTextChanged + filter + label update। Same architecture, अलग dialect: और जब Flutter अगली unit में आएगा, TextField का onChanged तीसरी बार वही SAME hook होगा। Unit 1 में 2 widgets बाकी हैं: image showmanship (ImageSlider, ImageSwitcher, SearchView) और फिर tabbed layout जो पूरी app reorganise करती है।

Summary

Key takeaways

  • AutoCompleteTextView = EditText + adapter-fed dropdown; setThreshold(n) gate करता है suggestions कब appear करें (minimum 1)।
  • यह suggest करता है, कभी restrict नहीं करता: सिर्फ़ listed values legal हों तो getText() validate कीजिए।
  • TextWatcher के 3 moments: beforeTextChanged (old text), onTextChanged (new text: live-search hook), afterTextChanged (Editable, modify कर सकते हैं)।
  • Firing order और text freshness अलग हैं: before पहले fire होता है पर old text देखता है।
  • जो watchers अपना text edit करते हैं वे idempotent होने चाहिए वरना हमेशा के लिए loop करते हैं।
  • Web live search (keyup + AJAX) जैसा same pattern: एक architecture, दो platforms।
  • Memory hook: before old देखता है, on new देखता है, after edit कर सकता है, edits को खुद रुकना चाहिए।

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Basic Attributes and Events of Important Android Widgets (UI)

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

AutoCompleteTextView, TextWatcher to EditText · Mobile Application Development - 2 (option B) · Gri-Learn