MaterialPreferences


Source link: https://github.com/yarolegovich/MaterialPreferences

MaterialPreferences

This library is a set of VIEWS (not Preferences) and is aimed to solve this problems:

  • Preferences look ugly on pre-lollipop.
  • Preferences are not flexible. For example, it can be problematic to embed them to another screen (especially for fragment-haters).
  • Preferences don't allow you to show custom selection dialogs.

Gradle

Add this into your dependencies block:

compile 'com.yarolegovich:mp:1.0.5'  

For LovelyInput you will also need this:

compile 'com.yarolegovich:lovelyinput:1.0.2' 

Wiki

Sample project that shows how to work with different library features is available as sample module. You can also download APK and play with it.

Contents

  1. Types of preferences
  2. UserInputModule
    Allows you to show any dialogs (or event not dialogs) you want, when some preferencesare clicked.
  3. StorageModule
    Allows you to save/retrieve values to/from any data source.
  4. LovelyInput
    Implementation of UserInputModule based on LovelyDialog library.

Types of preferences

There are 2 ViewGroup classes:

And a lot of AbsMaterialPreference subclasses:

Each preference contains optional title, summary and icon (icon can be tinted). Also for some preferences it is mandatory to set default value and key (at least when dealing with SharedPreference as StorageModule).

<com.yarolegovich.mp.AnyAbsMaterialPreferenceSubclass
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  app:mp_icon="@drawable/your_icon"
  app:mp_icon_tint="@color/textSecondary"
  app:mp_title="@string/your_title"
  app:mp_summary="@string/your_summary"
  app:mp_key="@string/pkey_your_key"
  app:mp_default_value="42|true|any string"/>

MaterialPreferenceScreen

ViewGroup.In essence - scrollable LinearLayout. Use it or not is a matter of preference, but it has some useful features.

public void setVisibilityController(int controllerId, List<Integer> controlledIds, boolean showWhenChecked);
 public void setVisibilityController(final AbsMaterialCheckablePreference controller, final List<Integer> controlledIds, final boolean showWhenChecked);

Sets some checkable preference to control visibility of views with specified ids. Last parameter is used to define when views should be visible (if preference is checked or not).

MaterialPreferenceScreen screen = (MaterialPreferenceScreen) findViewById(R.id.preference_screen);
 screen.setVisibilityController(R.id.pref_auto_loc, Arrays.asList(R.id.pref_location), false);

Now when our R.id.pref_auto_loc preference is checked/unchecked - R.id.pref_location will be hidden/shown.

MaterialPreferenceCategory

ViewGroup. Has optional attributes

app:mpc_title="@string/your_title" app:mpc_title_color="@color/your_color"

to specify a title and title color for category. In essence - CardView with vertical LinearLayout inside it.

MaterialStandardPreference

The simplest preference. Doesn't perform anything (until you set OnClickListener on it). Saves nothing.

MaterialRightIconPreference

The same as MaterialStandardPreference, but icon is on the right. Saves nothing.

AbsMaterialTextValuePreference

Sometimes I want to show current value of preference in summary or maybe on the right of the row. With sublcasses of MaterialTextInputPreference you have an option to do this by using:

<!-- default is notShow -->  app:mp_show_value="notShow|onBottom|onRight" 

attribute. It can take one of the listed values, that I think are pretty self-explanatory. Any subclass has access to this functionality.

AbsMaterialListPreference

Subclass of AbsMaterialTextValuePreference. Defines two attributes:

app:mp_entry_descriptions="@array/some_string_array" app:mp_entry_values="@array/some_string_array"

The first one contains values that will be shown in the dialog when preference is clicked. Second contains values that will be saved after some item is selected. If one attribute is omitted - another one will be used for both purposes.

MaterialChoicePreference

Subclass of AbsMaterialListPreference. On click shows dialog with items from mp_entry_descriptions, when any item is selected - item with corresponding index from mp_entry_values will be saved. Saves String value.

MaterialMultiChoicePreference

Subclass of AbsMaterialListPreference. On click shows dialog with items from mp_entry_descriptions, any number of items can be checked and after the dialog is dismissed - items from mp_entry_values with indices that correspond to indices of checked items will be saved. Saves Set value. Class also defines attribute:

app:mp_default_selected="@array/checked_items"

To specify items selected by default.

MaterialEditTextPreference

Subclass of AbsMaterialTextValuePreference. On click shows dialog with EditText and confirm button. After confirm button is clicked - text will be saved. Saves String value.

AbsMaterialCheckablePreference

Contains some checkable view and changes its state on click. All subclasses save boolean.

MaterialSwitchPreference

Subclass of AbsMaterialCheckablePreference. Contains SwitchCompat view on the right.

MaterialCheckboxPreference

Subclass of AbsMaterialCheckablePreference. Contains CheckBox view on the right.

MaterialColorPreference

Contains custom ColorView on the right that reflects currently selected color. Defines attributes:

app:mp_initial_color="@color/your_color" app:mp_border_color="@color/your_color" app:mp_border_width="@dimen/your_width" app:mp_indicator_shape="circle|square"

On click shows color picker dialog. By default it uses VintageChroma. Saves color int.

MaterialSeekBarPreference

Contains AppCompatSeekBar view under the summary and optional TextView that reflects current value. Defines attributes:

app:mp_max_val="12" app:mp_min_val="1" app:mp_show_val="true"

TextView with current value will be shown if mp_show_val is set to true (which is not by default). Saves int.

UserInputModule

Interface that defines methods called when some preferences are clicked:

  • MaterialEditTextPreference -> showEditTextInput(...)
  • MaterialChoicePreference -> showSingleChoiceInput(...)
  • MaterialMutltiChoicePreference -> showMultiChoiceInput(...)
  • MaterialColorPreference -> showColorSelectionInput(...)

If you want some special look of your dialogs you need to implement this interface together with UserInputModule.Factory. Then you need to set it as default UserInputModule or as UserInputModule for specific screen.

To see real example refer to this project.

Suppose you have classes:

public class MyFancyInputModule implements UserInputModule {
 ... 
}
  public class MyFancyInputModuleFactory implements UserInputModule.Factory {
 ... 
}

Then you need to do the following to set it as a default module:

MaterialPreferences.instance().setUserInputModule(new MyFancyInputModuleFactory());

Or set is as module for some specific screen:

MaterialPreferencScreen screen = (MaterialPreferenceScreen) findViewById(R.id.preference_screen);
 screen.setUserInputModule(new MyFancyInputModuleFactory());

StorageModule

Interface that defines methods called by preferences to save/retrieve value. This gives you additional flexibility, because preferences now can be used for different purposes - you can even initialize POJOs with the help of this feature.

To set your storage module follow the same procedure as with UserInputModule.

Suppose you have classes:

public class MyCoolStorageModule implements StorageModule {
 ... 
}
  public class MyCoolStorageModuleFactory implements StorageModule.Factory {
 ... 
}

Then you need to do the following to set it as a default module:

MaterialPreferences.instance().setStorageModule(new MyCoolStorageModuleFactory());

Or set is as module for some specific screen:

MaterialPreferencScreen screen = (MaterialPreferenceScreen) findViewById(R.id.preference_screen);
 screen.setStorageModule(new MyCoolStorageModuleFactory());

If you want to store data inside preferences, but not default - you can use:

new SharedPrefsStorageFactory("filename")

LovelyInput

Implementation of UserInputModule combined with my another library - LovelyDialog. For information on how to use it - check sample. You can use not only

setKeyIconMappings(Set<String, Integer> mappings);

but also

setKeyTitleMappings(Set<String, String> mappings);
 setKeyMessageMappings(Set<String, String> mappings);

Source code of module can serve you as an example of custom UserInputModule.

License

Copyright 2016 Yaroslav Shevchuk  Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License. You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 

Resources

MultiActionTextView allows to create Spannable TextView with and without under line.

PagerSlidingTabStrip is an interactive indicator to navigate between the different pages of a ViewPager. Inspired by astuetz/PagerSlidingTabStrip.

jraf-android-util is a collection of general purpose utilities for Android.

Why it exists

There is currently no way for an android application to catch and report ANR errors. If your application is not in the play store (either because you are still developing it or because you are distributing it differently), the only way to investigate an ANR is to pull the file /data/anr/traces.txt.

What it does

It sets up a watchdog timer that will detect when the UI thread stops responding. When it does, it raises an error with the main thread's stack trace.

XStream is a simple library to serialize objects to XML and back again.

Features:

  • Ease of use
  • No mappings required
  • Performance
  • Clean XML
  • Requires no modifications to objects
  • Full object graph support
  • Integrates with other XML APIs
  • Customizable conversion strategies
  • Security framework
  • Error messages
  • Alternative output format

droid-fu is a utility library for your daily Android needs.

NOTICE: This project has been discontinued. Developers are putting all efforts into ignition now, which is basically a rewritten but API breaking version of Droid-Fu that aims to have better project structure, better and less intrusive APIs, better documentation (we have samples now!) and proper release and issue management.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes