How to change the colour of Positive and negative button in Custom Alert dialog in android

前端 未结 5 1626
既然无缘
既然无缘 2020-12-29 07:12

What i am doing: I am creating a custom alert dialog

What i am trying to do: along with below code, How to change the color of act

5条回答
  •  旧时难觅i
    2020-12-29 07:34

    You can use the setOnShowListener method of the AlertDialog to get the buttons and apply a different color and their own listeners, here you have an example in Kotlin:

    val alert : AlertDialog?
    val alertView = LayoutInflater.from(context).inflate(R.layout.alert_add_product, null, false)
    
    val builder = AlertDialog.Builder(context)
        builder.setCancelable(false)
        builder.setView(alertView)
    
        /**Create positive and negative buttons**/
        builder.setPositiveButton(android.R.string.ok, null)
        builder.setNegativeButton(android.R.string.cancel, null)
    
        alert = builder.create()
    
        /**Listener called when the AlertDialog is shown**/
        alert.setOnShowListener {
    
             /**Get the positive button from the AlertDialog**/
             val positiveButton = alert.getButton(DialogInterface.BUTTON_POSITIVE)
    
             /**Set your color to the positive button**/
             positiveButton.setTextColor(ContextCompat.getColor(context, R.color.bluePrimaryDark))
    
             /**Set listener to the positive button**/
             positiveButton.setOnClickListener({
                  alert.dismiss()
             })
    
             /**Get the negative button from the AlertDialog**/
             val negativeButton = alert.getButton(DialogInterface.BUTTON_NEGATIVE)
    
             /**Set your color to the negative button**/
             negativeButton.setTextColor(ContextCompat.getColor(context, R.color.bluePrimaryDark))
    
             /**Set listener to the negative button**/
             negativeButton.setOnClickListener {
                  alert?.dismiss()
             }
        }
    
        alert.show()
    

提交回复
热议问题