RelativeLayout无法转换为TextWatcher:Firebase自动补全功能报错求助
Hey there, let's sort out this error you're facing! The RelativeLayout cannot be cast to android.text.TextWatcher crash happens because of a wrong cast when attaching your TextWatcher to the AutoCompleteTextView. Let's break down the problem and fix it step by step.
What's Causing the Error?
Looking at your code:
txt.addTextChangedListener((TextWatcher) getView());
getView() returns the root view of your layout, which is the RelativeLayout defined in your XML. You're trying to cast this layout to a TextWatcher—but RelativeLayout doesn't implement that interface at all. Even though your fragment/activity class does implement TextWatcher, you're passing the wrong object here.
Corrected Code
Here's the fixed version of your autoSearch method, plus notes on other small issues:
public void autoSearch(View view) { // Community list auto-search completion // Remove redundant context assignment, use getContext() directly instead String array1[] = firebaseComunityListArr.toArray(new String[firebaseComunityListArr.size()]); AutoCompleteTextView txt = (AutoCompleteTextView) view.findViewById(R.id.myAutoComplete); // Use "this" instead of casting getView()—your class implements TextWatcher! txt.addTextChangedListener(this); ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_dropdown_item_1line, array1); txt.setAdapter(adapter); txt.setTextColor(Color.GREEN); // Remove the duplicate setAdapter call below (you already set it above) // txt.setAdapter(adapter); } // Your existing TextWatcher methods are fine—keep them @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { }
Additional Notes
- Duplicate Adapter Assignment: You had two calls to
txt.setAdapter()—I removed the second one since it's redundant and could cause unexpected behavior ifadapterwasn't properly initialized elsewhere. - Context Handling: The line
this.context = context;was redundant because you can just usegetContext()directly in the ArrayAdapter constructor. - XML Layout: Your XML looks good—no issues there that would cause this specific crash.
Once you make these changes, the cast error should disappear, and your AutoCompleteTextView will correctly use your class's TextWatcher implementation.
内容的提问来源于stack exchange,提问作者golan

