βš™ A beautiful and extensible API for bulding preferences screen

Overview

Image

Material Preferences

Image

πŸ’» Installation

Download Licence

Add this in app's build.gradle file:

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

⚠ Attention! The package name has been changed from com.github.imangazalievm.material-prefs:xxx due to the transfer of the library to Maven Central.

⭐ Features

  • Convenient and extensible DSL
  • Flexible appearance settings
  • Unified view on Lollipop and Pre-Lollipop
  • Ability to use custom storage
  • Default prefs values
  • Light and dark themes

πŸ”₯ Usage

To start using the library you need to do 3 simple steps:

  1. Add MaterialPreferencesView in your layout
  2. Provide preferences storage:
    3.1 Default storage - DefaultPreferencesStorage
    3.1 Any custom storage which implements the PreferencesStorage interface
  3. Build prefs screen via MaterialPrefs DSL

If you want to use DefaultPreferencesStorage you have to provide initial values through DefaultValuesContainer.

Step 1 Place the MaterialPreferencesView in your layout:

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

Step 2 Create prefs storage and provide initial values:

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)

Step 3 Add pref items via MaterialPrefs DSL:

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

πŸ“„ Documentation

The library includes 4 modules:

  • core - contains main code: simple prefs, checkbox, switch
  • dialogs - dialogs prefs: single and multiple choice
  • date-time - date and time pickers
  • color-picker - color picker

Three last modules based on Material Dialogs library.

Core

Simple preference:

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

Switch:

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

Checkbox:

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

Label preference:

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

Dialogs

Single Choice:

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")
        )
    )
}

Multi Choice:

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")
        )
    )
}

Text Input:

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

DateTime

Date picker:

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

Time picker:

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

Date and picker:

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

ColorPicker

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

Custom preference item

To create custom preference item you have to do 3 steps:

Step 1: Create preference view class inherited from PreferenceView or BasePreferenceView.

If your view inherited from BasePreferenceView you have to implement createValueView method:

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)
    }

}

Step 2: Create preference class inherited from Preference or BasePreference and implement 3 methods:

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) {
    }

}

Third generic parameter of BasePreference is a type of data, that will be save in the preferences, so it must be one of the following types:

  • String
  • Int
  • Long
  • Float
  • Boolean

Step 3: Create extension method for MaterialSettings:

fun myPreference(builder: PreferenceBuilder<MyPreference>) {
    MyPreference(container, appearanceManager)
        .apply(builder)
        .also { addPreference(it) }
}
You might also like...
Trail is a simple logging system for Java and Android. Create logs using the same API and the library will detect automatically in which platform the code is running.

Trail Trail is a simple logging system for Java and Android. Create logs using the same API and the library will detect automatically in which platfor

Android library which makes it  easy to handle the different obstacles while calling an API (Web Service) in Android App.
Android library which makes it easy to handle the different obstacles while calling an API (Web Service) in Android App.

API Calling Flow API Calling Flow is a Android library which can help you to simplify handling different conditions while calling an API (Web Service)

Expirable Disk Lru Cache is a secure(with encryption) wrapper for [DiskLruCache](https://github.com/JakeWharton/DiskLruCache) that allows expiring of key/value pairs by specifying evictionTimeSpan. It has very simple API.

ExpirableDiskLruCache ExpirableDiskLruCache is a wrapper for DiskLruCache that allows expiring of key/value pairs by specifying evictionTimeSpan. It h

The REST API backend server for the Jalgaon CoHelp application.

API Service - Jalgaon CoHelp The REST API backend server for the Jalgaon CoHelp application. πŸ›  Technology / Tools used Kotlin: Programming language f

Perfect replacement for startActivityForResult(), based on the Activity Result API.
Perfect replacement for startActivityForResult(), based on the Activity Result API.

ActivityResultLauncher English | δΈ­ζ–‡ Activity Result API is an official tool used to replace the method of startActivityForResult() and onActivityResul

A modern contacts Android API.
A modern contacts Android API.

A modern contacts Android API.

SSI/NFC desktop/terminal API
SSI/NFC desktop/terminal API

Gimly SSI Card Terminal Gimly SSI Card Terminal is a REST API for Self Sovereign Identity interactions between apps, servers, terminals having an NFC

Consumer android from nutrition-framework API
Consumer android from nutrition-framework API

About This Project (work-in-progress πŸ‘· πŸ”§οΈ πŸ‘·β€β™€οΈ ⛏ ) Consumer Dari Nutrition Framework General Framework for Application Development Around Nutrition

gRPC and protocol buffers for Android, Kotlin, and Java.

Wire β€œA man got to have a code!” - Omar Little See the project website for documentation and APIs. As our teams and programs grow, the variety and vol

Comments
  • DateTimePicker not updating label when onSelected called

    DateTimePicker not updating label when onSelected called

    Hi, I noticed that the BaseDateTimePickerPreference isn't updating the label when you select a time, wasn't sure if this was a bug or feature? but the listSingleChoice updates the label on select.

    Before

     protected fun onSelected(value: Calendar) {
            saveValue(value.timeInMillis)
            onValueSelected?.invoke(value)
        }
    

    After

      protected fun onSelected(value: Calendar) {
            saveValue(value.timeInMillis)
            onValueSelected?.invoke(value)
            val text = valueConverter?.invoke(value) ?: defaultFormatter.format(value.time)
            view.setLabelText(text)
    	}
    

    It was a quick fix and likely a more elegant solution exists, but thought I'd share in case others found this issue.

    opened by scottyab 0
Owner
Mahach Imangazaliev
Mahach Imangazaliev
Screen Capture Utils - A plugin to handle screen capture events on android and ios

Screen Capture Utils A plugin to handle screen capture events on android and ios ?? Initialize SDK late ScreenCaptureUtils screenCaptureUtils;

Chiziaruhoma Ogbonda 41 Apr 12, 2022
A dual screen capable home screen launcher for Android phones with dual displays, such as the LG V60, G8X & Velvet.

Duality-Launcher A dual screen capable home screen launcher for Android phones with dual displays, such as the LG V60, G8X & Velvet

Russ Nash 6 Sep 8, 2022
Reactor is key value database and is a great alternative to Shared Preferences.

Reactor Reactor is a fast and secure key-value library for Android, and has an embedded database based on the JSON structure and is a great alternativ

mr amir abbas 37 Oct 30, 2022
Android Shared preference wrapper than encrypts the values of Shared Preferences. It's not bullet proof security but rather a quick win for incrementally making your android app more secure.

Secure-preferences - Deprecated Please use EncryptedSharedPreferences from androidx.security in preferenced to secure-preference. (There are no active

Scott Alexander-Bown 1.5k Dec 24, 2022
Secure Preference Manager for android. It uses various Encryption to protect your application's Shared Preferences.

Secure-Pref-Manager ##Secure Preference Manager is a simple Library to help you protect your Shared Preferences. Secure Preference Manager for android

Prashant Solanki 72 Nov 25, 2022
Preferences data store example

DataStore Example this example shows how you can use data store to store data in key value pairs and get rid of shared preferences Medium Article: htt

Kashif Mehmood 24 Dec 15, 2022
AplicaciΓ³n Android para comprender como funciona el listado y las shared preferences

READ.ME Este proyecto tiene como finalidad explicar como se debe utilizar un RecyclerView con una vista bindeada a este. En el proyecto se puede ver c

Carlos MuΓ±oz Bustamante 4 Apr 12, 2022
A beautiful set of predefined colors and a set of color methods to make your Android development life easier.

Colours is a port of the Colours Library for iOS made by my good friend Ben Gordon. You can find that project here. Installation Maven Central Colours

Matthew York 634 Dec 28, 2022
A small utility to record Android device screen to a GIF

RoboGif A small utility to record Android device screen to an optimized GIF so you can paste it to GitHub or a similar service. Requirements Python 2.

Jernej Virag 526 Dec 9, 2022
Simple Keyboard can adjustable keyboard height for more screen space

Simple Keyboard About Features: Small size (<1MB) Adjustable keyboard height for more screen space Number row Swipe space to move pointer Delete swipe

Raimondas Rimkus 681 Dec 27, 2022