如何使字符计数器排除白色空间和行间距?

问题描述 投票:1回答:1

enter image description here

正如您在上图中看到的,我在右下角有多行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很好。这里出了什么问题?

android kotlin android-edittext
1个回答
2
投票

我解决了它改变你的方法到这个:

private fun setWordsCounter(words: CharSequence?) {
    val rawInputString = words.toString()
        .trim()
        .replace(" ","")
        .replace("\n","")
    numberOfInputWords = rawInputString.length
}

它是做什么的,首先trim() - 删除所有的空白区域,然后删除所有的new lines

输出是这一个:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.