0

Actually I met a problem with dynamically adjusting the textview gravity which depends on its line count.

I read this article, but I just don't really understand the difference about threading techniques, just like textview.post(), runOnUiThread{}, GlobalScope.launch(Dispatchers.Main), Thead{}.start().

TLDR, short question is "Why the codes below should be run in the post scope?"

private fun setText(text : String) {
    textView.text = text

    textView.post {
        if (textView.lineCount > 1) {
            textView.gravity = Gravity.START
        }else {
            textView.gravity = Gravity.CENTER
        }
    }
}

and another short question is "Why it doesn't work in the GlobalScope.launch(Dispatchers.Main)?"

This is my try:

private fun setText(text : String) {
    textView.text = text

    GlobalScope.launch(Dispatchers.Main) {
        if (textView.lineCount > 1) {
            textView.gravity = Gravity.START
        }else {
            textView.gravity = Gravity.CENTER
        }
    }
}

I tried to put it into GlobalScope.launch(Dispatchers.Main), but it sometimes works and sometimes doesn't work. Also, I tried to make it without textView.post(), and it just doesn't work. The source code of getLineCount() doesn't seem to be async operation?

Any suggestion is welcome, thanks for everything.

rongson
  • 13
  • 3
  • Read about post() https://stackoverflow.com/questions/13840007/what-exactly-does-the-post-method-do – Ashok Kumar Sep 10 '19 at 02:50
  • @AshokKumar Thanks for your reply, I've read related articles about `post()` and `runOnUiThread`, and knowing that `post` will be enqueued to run, `runOnUiThread` will run directly. Can you please explain why these code must be in the `post()` scope? ``` if (textView.lineCount > 1) { textView.gravity = Gravity.START }else { textView.gravity = Gravity.CENTER } ``` – rongson Sep 10 '19 at 03:20

0 Answers0