在新的 MaterialDatePicker 中更改按钮文本

Change button text in new MaterialDatePicker

我正在将日历组件迁移到新的材料库,MaterialDatePicker,但是我在做一些像更改确认按钮文本的名称这样简单的事情时遇到了问题

以前用这个就够了

datePickerDialog.setButton(DatePickerDialog.BUTTON_POSITIVE, getString(R.string.save), datePickerDialog)

但是现在我找不到任何public方法

val picker = Builder.datePicker()
            picker.addOnPositiveButtonClickListener { selection: Long ->
                saveListPosition()
                accountDetailsPresenter.editDate(selection, transaction, product, "")
            }
picker.show(childFragmentManager, picker.toString())

目前(1.1.0-beta021.2.0-alpha02)您无法以编程方式执行此操作。

但是您可以覆盖项目中的现有字符串,但此 变通办法可以在下一版本中停止到 运行

对于确认和取消按钮,将这些字符串放入您的项目中:

  <string name="mtrl_picker_confirm" description="Button text to indicate that the widget will save the user's selection [CHAR_LIMIT=16]">.....</string>
  <string name="mtrl_picker_cancel" description="Button text to indicate that the widget will ignore the user's selection [CHAR_LIMIT=16]" translatable="false">...</string>

有一种变通方法可以以编程方式设置按钮文本,最重要的是不适用于整个项目。

  1. 创建日期选择器

         val picker : MaterialDatePicker<*> = MaterialDatePicker.Builder.datePicker().build()
    
  2. 通过 ID 查找正面或负面按钮。

         picker?.view?.findViewById<Button>(com.google.android.material.R.id.confirm_button)?.text =
             "Your text here"
    
         picker?.view?.findViewById<Button>(com.google.android.material.R.id.cancel_button)?.text =
             "Your text here"
    

更新于 1.4.0

我们仍然没有 public 方法来为否定按钮和肯定按钮提供自定义文本。出于某种原因,使用 findViewById<Button>(com.google.android.material.R.id.confirm_button).text = "some text" 不适合我。而是将以下行添加到您的字符串 xml 中以使用您的自定义文本。 (这将对整个应用程序产生影响!)这些与提供的 @Gabriele Mariotti 之间的区别是更新的字符串资源 ID。

<string description="Confirms the selection [CHAR_LIMIT=12]" name="mtrl_picker_save">Your positive button text</string>

<string name="cancel">Your negative button text</string>
MaterialDatePicker.Builder.datePicker().apply {
    setTitleText("Start Date")
    setSelection(startDate.time)
}.build().apply {
    doOnStart {
        view?.findViewById<Button>(com.google.android.material.R.id.confirm_button)?.text = "Select"
        view?.findViewById<Button>(com.google.android.material.R.id.cancel_button)?.text = "Clear"
    }
    addOnPositiveButtonClickListener { date ->
        startDate = Date(date)
    }
    addOnNegativeButtonClickListener {
        setDate(null)
    }
}.show(childFragmentManager, "changeDate")