开发酒店审计APP时,使用EditText的getTag()返回null问题求助
Hey there! Let's work through that getTag() returning null issue with your dynamically created EditTexts. Here are the most common fixes and checks to resolve this:
First, confirm you're actually setting the tag on your EditText
This is the #1 reasongetTag()returns null—if you never calledsetTag(), there's nothing to retrieve! When you dynamically create your EditText in the loop, make sure to assign a tag right after initializing it. For example:// Inside your loop creating TableRows/EditTexts EditText answerEt = new EditText(getActivity()); // Set tag with the relevant question data or index answerEt.setTag(questionList.get(i)); // Or use an index if that's more useful: answerEt.setTag(i); row.addView(answerEt);Check if the tag is being overwritten or lost
Sometimes subsequent code (like view binding libraries, layout updates, or view recycling) can overwrite or clear the tag. If you're using a RecyclerView or similar view container, ensure you re-set the tag every time the view is bound/recycled—don't rely on cached tag values.Verify you're calling getTag() on the correct EditText instance
It's easy to accidentally reference a different EditText than the one you tagged. Add a quick log to confirm the object identity:EditText targetEt = (EditText) findViewById(yourEtId); Log.d("TAG_DEBUG", "Target EditText hash: " + targetEt.hashCode()); // Compare this hash with the one from the EditText you created dynamicallyIf the hashes don't match, you're calling
getTag()on the wrong view.Double-check layout inflation timing (if using inflated layouts)
If you're usingLayoutInflaterto load pre-made layouts with EditTexts, make sure you set the tag after inflating and finding the EditText in the layout. For example:View rowView = LayoutInflater.from(getActivity()).inflate(R.layout.audit_question_row, row, false); EditText answerEt = rowView.findViewById(R.id.et_audit_answer); // Set tag after retrieving the EditText from the inflated view answerEt.setTag(questionList.get(i)); row.addView(rowView);Use keyed tags to avoid conflicts
If you need multiple tags on the same EditText, use thesetTag(int key, Object tag)overload to prevent clashes with system or library tags. Define a unique key (like a constant) and use it to set/get the tag:// Define a constant key (put this in a constants class or your activity) private static final int TAG_AUDIT_QUESTION = 1001; // Set the keyed tag answerEt.setTag(TAG_AUDIT_QUESTION, questionList.get(i)); // Retrieve the tag using the same key Question currentQuestion = (Question) answerEt.getTag(TAG_AUDIT_QUESTION);
内容的提问来源于stack exchange,提问作者user7735493

