align AlertDialog buttons to center

前端 未结 9 1894
无人共我
无人共我 2020-12-06 09:09

I use this codes for Android (Java) programming:

public static MessageBoxResult showOk(
        Context context, String title, String message, String okMessa         


        
9条回答
  •  再見小時候
    2020-12-06 09:44

    Ended up with this extension for Kotlin:

    fun AlertDialog.withCenteredButtons() {
        val positive = getButton(AlertDialog.BUTTON_POSITIVE)
        val negative = getButton(AlertDialog.BUTTON_NEGATIVE)
    
        //Disable the material spacer view in case there is one
        val parent = positive.parent as? LinearLayout
        parent?.gravity = Gravity.CENTER_HORIZONTAL
        val leftSpacer = parent?.getChildAt(1)
        leftSpacer?.visibility = View.GONE
    
        //Force the default buttons to center
        val layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
    
        layoutParams.weight = 1f
        layoutParams.gravity = Gravity.CENTER
    
        positive.layoutParams = layoutParams
        negative.layoutParams = layoutParams
    }
    

    And use with:

    .show().withCenteredButtons()
    

提交回复
热议问题