El Arsenal de Android – Preferencias

? Instalación

Agrega esto en la aplicación build.gradle expediente:

implementation 'com.github.imangazalievm.material-prefs:core:<version>'
implementation 'com.github.imangazalievm.material-prefs:dialogs:<version>'
implementation 'com.github.imangazalievm.material-prefs:date-time:<version>'
implementation 'com.github.imangazalievm.material-prefs:color-picker:<version>'

Caracteristicas

  • DSL cómodo y extensible
  • Configuración de apariencia flexible
  • Vista unificada de Lollipop y Pre-Lollipop
  • Capacidad para utilizar archivos personalizados
  • Valores predeterminados de preferencia
  • Temas claros y oscuros

? Uso

Para comenzar a utilizar la biblioteca, debe realizar 3 sencillos pasos:

  1. insertar MaterialPreferencesView en tu diseño
  2. Proporcionar almacenamiento de preferencia: 3.1 Almacenamiento predeterminado – 3.1 Cualquier almacenamiento personalizado que implemente la extensión PreferencesStorage interfaceDefaultPreferencesStorage
  3. Crear pantalla de preferencias a través de MaterialPrefs DSL

Si quieres usar DefaultPreferencesStorage tienes que suministrar los valores iniciales a través de DefaultValuesContainer.

Paso 1 Colocar el MaterialPreferencesView en su diseño:

<com.imangazalievm.materialprefs.views.MaterialPreferencesView
        android:id="@+id/prefsView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

Paso 2 Cree el almacenamiento de preferencias y proporcione los valores iniciales:

val defValues = defaultPrefValues {
    "my_string" to "Jhon Doe"
    "my_int" to 99
    "my_long" to 5L
    "my_float" to 2.5f
    "my_boolean" to true
}

val storage = defaultPrefsStorage("my_prefs", defValues)

Paso 3 Agregue elementos pref a través de MaterialPrefs DSL:

prefs(prefsView, storage) {
    category("My category") {
         preference {
            title("My pref item")
            icon(R.drawable.my_icon)
            onClick {
                //my action
            }
        }
    }
}
            

? Documentación

La biblioteca incluye 4 módulos:

  • núcleo – contiene el código principal: preferencias simples, casilla de verificación, interruptor
  • diálogos – Preferencias de diálogo: opción única y múltiple
  • cita – selectores de fecha y hora
  • selector de color – selector de color

Tres módulos más recientes basados ​​en la biblioteca Material Dialogs.

Núcleo

Preferencia simple:

preference {
    title("Title")
    summary("My description")
    icon(R.drawable.ic_my_icon)
    showArrow(true)
    onClick {
        //my action
    }
}

Cambiar:

switch("my_key") {
    title("Title")
    summary("My description")
    onChecked { isChecked ->
        //my action
    }
}

Casilla de verificación:

checkbox("my_key") {
    title("Title")
    summary("My description")
    onChecked { isChecked ->
        //my action
    }
}

Preferencia de etiqueta:

labelPreference("my_key", String::class) {
    title("Title")
    onClick {
        //my action
    }
}

Diálogos

Elección única:

listSingleChoice("my_key", String::class) {
    title("Title")
    icon(R.drawable.ic_my_icon)
    showRadioButtons(true)
    items(
        listOf(
            ListItem("ar", "Arabic"),
            ListItem("en", "English"),
            ListItem("ru", "Russian")
        )
    )
}

Opción multiple:

listMultiChoice("my_key", String::class) {
    title("Title")
    allowEmptySelection(false)
    //required
    listValuesSerializer { it.joinToString() }
    //required
    listValuesDeserializer {
        if (it.isNotEmpty()) {
            it.split(",")
                .map { number -> number.trim().toInt() }
        } else emptyList()
    }             
    items(
        listOf(
            ListItem("one", "Item 1"),
            ListItem("two", "Item 2"),
            ListItem("three", "Item 3")
        )
    )
}

Ingresando texto:

textInput("my_key") {
    title("Title")
    icon(R.drawable.ic_username)
    onNewInput { 
        //my action       
    }
}

Cita

Selector de fechas:

datePicker("my_key") {
    title("Title")
    val formatter = SimpleDateFormat("dd.MM.yyyy ", Locale.US)
    valuePresenter { formatter.format(it) }
    onValueSelected {
        //my action
    }
}

Selector de tiempo:

timePicker("my_key") {
    title("Title")
    val formatter = SimpleDateFormat("hh:mm ", Locale.US)
    valuePresenter { formatter.format(it) }
    onValueSelected {
        //my action
    }
}

Fecha y selección:

dateTimePicker("my_key") {
    title("Title")
    val formatter = SimpleDateFormat("hh:mm dd.MM.yyyy ", Locale.US)
    valuePresenter { formatter.format(it) }
    onValueSelected {
        //my action
    }
}

Selector de color

colorPicker("my_key") {
    title("Title")
    val colors = intArrayOf(Color.RED, Color.GREEN, Color.BLUE)
    colors(colors)
    onColorSelected {
        //my action
    }
}

Elemento de preferencia personalizado

Para crear un elemento de preferencia personalizado, debe realizar 3 pasos:

Paso 1: Crea la clase de vista de preferencias heredada de PreferenceView o BasePreferenceView.

Si su visión fue heredada de BasePreferenceView tienes que implementar createValueView método:

class MyPreferenceView(
    context: Context,
    attrs: AttributeSet? = null,
    themeResId: Int = 0
) : BasePreferenceView(context, attrs, themeResId) {

    override fun createValueView(parent: ViewGroup): View {
        return parent.inflate(R.layout.my_pref_view)
    }

}

Paso 2: Cree una clase de preferencia heredada de Preference o BasePreference e implementar 3 métodos:

abstract class MyPreference(
    key: String,
    container: PrefsContainer,
    private val appearanceManager: PreferencesAppearance
) : BasePreference<MyPreference, MyPreferenceView, String>(
    container = container,
    key = key,
    appearanceManager = appearanceManager
) {

    override fun createView(): V {
    }

    override fun loadValue(view: V) {
    }
 
    override fun initView(view: V) {
    }

}

Tercer parámetro genérico de BasePreference es un tipo de datos, que se guardará en preferencias, por lo que debe ser uno de los siguientes tipos:

  • Cuerda
  • En t
  • Largo
  • Flotante
  • Booleano

Paso 3: Cree un método de extensión para MaterialSettings:

fun myPreference(builder: PreferenceBuilder<MyPreference>) {
    MyPreference(container, appearanceManager)
        .apply(builder)
        .also { addPreference(it) }
}

? Licencia

The MIT License

Copyright (c) 2020 Mahach Imangazaliev

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

.

Compruebe también

Blog para desarrolladores de Android: #WeArePlay | Conozca a las fundadoras que cambiaron la vida de las mujeres: Historias del Mes de la Historia de la Mujer

Publicado por Leticia Lago – Marketing para Desarrolladores Para celebrar el Mes de la Historia …

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *