Lets take this for example...
entryText.addTextChangedListener(new TextWatcher() {
TextView wordCount = (TextView) findViewById(R.id.wordCount);
TextView charCount = (TextView) findViewById(R.id.charCount);
@Override
public synchronized void afterTextChanged(Editable s) {
wordCount.setText("W: " + String.valueOf(ChosenFile.countWords(entryText.getText().toString())));
charCount.setText("C: " + Integer.toString(entryText.getText().length()));
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
});
Are new instances of textviews wordCount and CharCount created each time the listener is invoked? Would it be better to make them global?
How is memory handled? Lets say new instances are created, how does that affect memory?
1 Answer 1
The variables wordCount and charCount are created and initialized only when the TextWatcher object is created and added as a listener. No new instance is created every time the text changes.
-
This answer is correct. I wonder why it got downvoted.COME FROM– COME FROM2016年01月11日 09:43:08 +00:00Commented Jan 11, 2016 at 9:43
findViewById()
we cannot say for sure.addTextChangedListener
is called? Or whenafterTextChanged
is called?afterTextChanged
context, @FlorianF answer bellow is correct. ForaddTextChangedListener
context, @Snowman context is correct. It depends on if thefindViewById
creates a new instance or not.