@@ -3,6 +3,8 @@ package com.simplemobiletools.notes.fragments
33import android.graphics.Typeface
44import android.os.Bundle
55import android.support.v4.app.Fragment
6+ import android.text.Editable
7+ import android.text.TextWatcher
68import android.text.method.LinkMovementMethod
79import android.text.util.Linkify
810import android.util.TypedValue
@@ -95,6 +97,7 @@ class NoteFragment : Fragment() {
9597 super .onResume()
9698
9799 val config = context!! .config
100+
98101 view.notes_view.apply {
99102 typeface = if (config.monospacedFont) Typeface .MONOSPACE else Typeface .DEFAULT
100103
@@ -113,10 +116,45 @@ class NoteFragment : Fragment() {
113116 setSelection(if (config.placeCursorToEnd) text.length else 0 )
114117 }
115118 }
119+
120+ if (config.showWordCount) {
121+ view.notes_view.addTextChangedListener(textWatcher)
122+ view.notes_counter.visibility = View .VISIBLE
123+ setWordCounter(view.notes_view.text)
124+ }
125+ else {
126+ view.notes_counter.visibility = View .GONE
127+ }
116128 }
117129
118130 override fun onPause () {
119131 super .onPause()
120132 saveText()
133+
134+ removeTextWatcher()
135+ }
136+
137+ private fun removeTextWatcher () {
138+ // Avoid memory leak
139+ view.notes_view.removeTextChangedListener(textWatcher)
140+ }
141+
142+ private fun setWordCounter (text : Editable ) {
143+ // Replace new lines with space
144+ val wordArray = text.toString().replace(" \n " , " " ).split(" " )
145+ // Count only items which are not empty
146+ notes_counter.text = wordArray.count { it.isNotEmpty() }.toString()
147+ }
148+
149+ private var textWatcher: TextWatcher = object : TextWatcher {
150+ override fun beforeTextChanged (s : CharSequence , start : Int , count : Int , after : Int ) {
151+ }
152+
153+ override fun onTextChanged (s : CharSequence? , start : Int , before : Int , count : Int ) {
154+ }
155+
156+ override fun afterTextChanged (editable : Editable ) {
157+ setWordCounter(editable)
158+ }
121159 }
122160}
0 commit comments