正如您在上图中看到的,我在右下角有多行edittext和一个单词计数器textview。
我希望计数器根据编辑文本中的字符输入数量显示数字“7”。所以我想排除空格和行空格(输入,\ n)在字计数器中计算。
但不幸的是我得到'9'而不是'7'。这是我使用的代码:
class CreateEventDescriptionFragment : Fragment() {
lateinit var fragmentView : View
lateinit var inputEventDescriptionEditText : EditText
lateinit var wordsCounterTextView: TextView
lateinit var mContext : Context
lateinit var mActivity : FragmentActivity
override fun onAttach(context: Context) {
super.onAttach(context)
mContext = context
activity?.let { mActivity = it }
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
fragmentView = inflater.inflate(R.layout.fragment_create_event_description, container, false)
setUpViewsDeclaration()
setUpListeners()
return fragmentView
}
private fun setUpViewsDeclaration() {
inputEventDescriptionEditText = fragmentView.findViewById(R.id.editText_event_description_input)
wordsCounterTextView = fragmentView.findViewById(R.id.textView_words_counter_event_description)
}
private fun setUpListeners() {
inputEventDescriptionEditText.addTextChangedListener(object: TextWatcher {
override fun afterTextChanged(s: Editable?) {
setWordsCounter(s)
wordsCounterTextView.text = "$numberOfInputWords"
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
setWordsCounter(s)
wordsCounterTextView.text = "$numberOfInputWords"
}
})
}
private fun setWordsCounter(words: CharSequence?) {
val rawInputString = words.toString().trim()
val removedEmptyLineInputString = rawInputString.replace("(?m)^[ \t]*\r?\n", "")
val removedEmptySpaceInputString = removedEmptyLineInputString.replace(" ", "")
numberOfInputWords = removedEmptySpaceInputString.count()
}
}
Java很好。这里出了什么问题?