How to write style to error text of EditText in android?

前端 未结 7 1807
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 12:37

I\'m trying to write new custom style for my android application. I need to give style to errorText which appears after setting setError in EditText

7条回答
  •  Happy的楠姐
    2020-11-27 12:44

    I have not found any solution to edit error style, but I have created custom EditText with error popup. Hopefully, it will help:

    
    import android.content.Context
    import android.util.AttributeSet
    import android.view.Gravity
    import android.view.LayoutInflater
    import android.widget.EditText
    import android.widget.LinearLayout
    import android.widget.PopupWindow
    import android.widget.TextView
    import androidx.annotation.StringRes
    
    class ErrorEditText : EditText {
    
        constructor(context: Context) : super(context)
    
        constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    
        constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
    
        private var errorPopup: PopupWindow? = null
    
        fun showError(message: String) {
            showErrorPopup(message)
        }
    
        fun showError(@StringRes messageResId: Int) {
            showErrorPopup(context.getString(messageResId))
        }
    
        fun dismissError() {
            post {errorPopup?.dismiss() }
        }
    
          private fun showErrorPopup(message: String) {
            post {
                dismissError()
                val inflater = (context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater)
                val view = inflater.inflate(R.layout.edit_text_error, null, false)
                errorPopup =
                    PopupWindow(view, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
                errorPopup?.contentView?.findViewById(R.id.message)?.text = message
                errorPopup?.showAsDropDown(this, 0, 10, Gravity.START)
            }
        }
    }
    

    You can use methods: showError(message: String) or showError(@StringRes messageResId: String) to show the error and method dismissError() to hide it.

    Keep in mind that pop-ups are bound with activity lifecycle if you are using multiple fragments to navigate through the app, remember about closing them when navigating.

    Here is my edit_text_error layout used for popup:

    
    
    
        
    
            
    
        
    
    

    If you'd like to move popup to the end of EditText, please change last line in showErrorPopup() method to: errorPopup?.showAsDropDown(this, 0, 10, Gravity.END)

    You can manipulate the position of the popup by modifying gravity or x and y parameters of the showAsDropDown(view: View, x: Int, y: Int, gravity: Gravity) method

提交回复
热议问题