How to get number of lines of TextView?

前端 未结 10 2493
萌比男神i
萌比男神i 2020-11-28 09:29

I want to get the number of lines of a text view

textView.setText(\"Test line 1 Test line 2 Test line 3 Test line 4 Test line 5.............\")
10条回答
  •  不知归路
    2020-11-28 10:13

    You could also use PrecomputedTextCompat for getting the number of lines. Regular method:

    fun getTextLineCount(textView: TextView, text: String, lineCount: (Int) -> (Unit)) {
        val params: PrecomputedTextCompat.Params = TextViewCompat.getTextMetricsParams(textView)
        val ref: WeakReference? = WeakReference(textView)
    
        GlobalScope.launch(Dispatchers.Default) {
            val text = PrecomputedTextCompat.create(text, params)
            GlobalScope.launch(Dispatchers.Main) {
                ref?.get()?.let { textView ->
                    TextViewCompat.setPrecomputedText(textView, text)
                    lineCount.invoke(textView.lineCount)
                }
            }
        }
    }
    

    Call this method:

    getTextLineCount(textView, "Test line 1 Test line 2 Test line 3 Test line 4 Test line 5.............") { lineCount ->
         //count of lines is stored in lineCount variable
    }
    

    Or maybe you can create extension method for it like this:

    fun TextView.getTextLineCount(text: String, lineCount: (Int) -> (Unit)) {
        val params: PrecomputedTextCompat.Params = TextViewCompat.getTextMetricsParams(this)
        val ref: WeakReference? = WeakReference(this)
    
        GlobalScope.launch(Dispatchers.Default) {
            val text = PrecomputedTextCompat.create(text, params)
            GlobalScope.launch(Dispatchers.Main) {
                ref?.get()?.let { textView ->
                    TextViewCompat.setPrecomputedText(textView, text)
                    lineCount.invoke(textView.lineCount)
                }
            }
        }
    }
    

    and then you call it like this:

    textView.getTextLineCount("Test line 1 Test line 2 Test line 3 Test line 4 Test line 5.............") { lineCount ->
         //count of lines is stored in lineCount variable
    }
    

提交回复
热议问题