Search code examples
androidkotlinandroid-edittexttrim

Strange Problem with EditText() - Android Kotlin


I'm facing this odd issue:

    // definition
    var myEditText: EditText? = null

    .
    .
    .

    // instantiation
    myEditText = EditText(this)
    myEditText?.setSingleLine(true)
    myEditText?.setTextColor(Color.YELLOW)
    myEditText?.setBackgroundColor(Color.RED)
    myEditText?.setPadding(10, 0, 10, 0)
    myEditText?.gravity = Gravity.CENTER_VERTICAL
    myEditText?.inputType = InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS
    myEditText?.setOnFocusChangeListener { view, hasFocus -> ...

    rootView.addView(myEditText)

    .
    .
    .

    if (myEditText?.text == null || myEditText?.text.trim() == "") {

        println("it's blank!")   // doesn't execute

    } else {

        println(">>>" + myEditText?.text.trim() + "<<<")

    }

    // output: >>><<<

The EditText() control has been instantiated properly and appears correctly on the screen. I'm able to type in text and it will return the entries correctly.

But why can't it recognize that the text box is empty?


Solution

  • myEditText?.text.toString()
    

    You should use toString()

    Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.