3

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
    Do the answers to Is repeatedly instantiating an anonymous class wasteful? on SO answer your question? – Ixrec Jan 11 '16 at 0:05
  • 3
    Without knowing the implementation of findViewById() we cannot say for sure. – user22815 Jan 11 '16 at 1:18
  • by "each time the listener is invoked", Do you mean when addTextChangedListener is called? Or when afterTextChanged is called? – Caleb Jan 11 '16 at 2:21
  • @Caleb For argument, lets say both. – Captain Save A Hoe Jan 11 '16 at 3:42
  • For afterTextChanged context, @FlorianF answer bellow is correct. For addTextChangedListener context, @Snowman context is correct. It depends on if the findViewById creates a new instance or not. – Caleb Jan 11 '16 at 22:04
3

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 Jan 11 '16 at 9:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.