Open In App

How to Use MaterialPreferenceLibrary Library in Android?

Last Updated : 18 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In Android Development developers often use libraries that help create UI. Sometimes creating a UI like RecyclerView can be hectic that’s why we use different libraries and the material preference library makes making UI easy. In this article, we are going to learn about the material preference library. We will see the practical use of the material preference library in Android, In a detailed code explanation. We are going to learn about all points given below.

  • What is Material Preference Library?
  • Features of Material Preference Library
  • How to use Material preference Library in Android?

What is Material Preference Library?

The material preference library is an open-source library used for UI development. It makes making UI easy, Lets understand by an example Suppose we want to show a recycler view in my activity so for that, we have to create a custom RecyclerView Adapter which is a lot of code, and not only that but we have to make another separate XML file for that. This takes a lot of time and hard work, But with the help of this library we can save a lot of time and it would be a lot easier.

Features of Material Preference Library

  • Material design
  • Modular backend
  • Easy to implement
  • Simple but intuitive API
  • Dynamic item support

How to use Material Preference Library in Android?

We will see a detailed procedure about using it step by step with the help of an Example android application. So follow all the following steps.

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Add dependencies

As we know there are two gradle files in an android project. One is project level and another is app module level. So copy the following dependencies and paste them into your App-level build.gradle file. 

  implementation ‘com.github.filol:material-preference-library:1.0’

And also copy the following maven URL and paste it into the Project-Level build.gradle file.

maven {   url ‘https://jitpack.io’   }

Step 3: Updating Themes.xml

Now we have to go to the Themes.xml file which is at res->values->themes. set the theme parent to any one of the following inside themes file

Theme.mp.Light (light theme with light toolbar)
Theme.mp.Light.DarkActionBar (light theme with dark toolbar)
Theme.mp.Dark (dark theme with dark toolbar)
Theme.mp.Dark.LightActionBar (dark theme with light toolbar)

Nowadays, in android  there are two themes.xml are present. One is theme.xml(light mode) another is themes.xml(dark mode). the app sets anyone of them according to what user has set in the mobile. like we use everyday in our mobiles , light mode and dark mode, our app directly switches between those two files as well. So in the themes.xml (light) file, you can set the parent to 

Theme.mp.Light (light theme with light toolbar)
Theme.mp.Light.DarkActionBar (light theme with dark toolbar)

And in the themes.xml (dark) you can set parent to any one of the below

Theme.mp.Dark (dark theme with dark toolbar)
Theme.mp.Dark.LightActionBar (dark theme with light toolbar)

You have to add it like its added in the theme given below, i.e:  parent=”Theme.mp.Dark”

XML




<style name="Theme.ProjectName" parent="Theme.mp.Dark" >
        <!-- Primary brand color. -->
        <item name="colorPrimary">#0F9D58</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/black</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_200</item>
        <item name="colorOnSecondary">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
    </style>


Step 4: Extending the current Activity with MaterialPreferenceActivity

Before writing any code in our Activity we must make sure that our activity extends MaterialPreferenceActivity. We have to do it manually every time as by default our activity is extending AppCompact Activity. We don’t only have to extend but to remove the previous methods and add new methods which are inheriting from MaterialPreference Activity. After doing that our code will look like. 

Java




public class MainActivity extends MaterialPreferenceActivity {
  
    @Override
    @NonNull
    protected MaterialPreferenceList getMaterialPreferenceList(@NonNull Context context) {
        // This creates an empty screen, 
        // add cards with .addCard()
        return new MaterialPreferenceList.Builder().build(); 
    }
  
    @Override
    protected CharSequence getActivityTitle() {
        return "GFG MPLib Tutorial";
    }
  
}


The method getActivityTitle() returns a string that is nothing but the title of our toolbar. In simple words, we can say that this method is used for setting the toolbar in our activity. It will execute the following output 

Output:

Output

Step 5: Adding Cards

Now here comes the main part, Up to now we just have added the Toolbar and now we are going to add a Card to our Screen. Usually, it would take a lot of XML and java code but with the library, we are using it becomes easy. Let’s see how

Java




MaterialPreferenceCard.Builder cardBuilder = new MaterialPreferenceCard.Builder();
cardBuilder.addItem(new MaterialPreferenceTitleItem.Builder()
        .text("Material Preference Library")
        .icon(R.mipmap.ic_launcher)
        .build());


Here, we are making a card object and adding text and icon just by using the text and icon methods. There are 4 card items we can add into a card, in the above code we have used MaterialPreferenceTitleItem. It will produce the following output

We can see just with 4 lines of code we are able to see a RecyclerView with 1 size.

Step 6: Items in Cards

There are currently 4 types of items you can add to a card – MaterialPreferenceTitleItem, MaterialPreferenceActionItem, MaterialPreferenceCheckboxItem and MaterialPreferenceSwitchItem. Other types of items are planned, for example, “person” items that feature buttons to showcase a single person. Feel free to submit a PR or Issue for more item ideas. MaterialPreferenceActionItem: Standard item with text, icon, and optional subtext. MaterialPreferenceTitleItem: Larger item with large icon (e.g. app icon) and larger text. MaterialPreferenceTitleItem is created with MaterialPreferenceTitleItem.Builder() and lets you specify text and an icon.

Now we will use the MaterialPreferenceActionItem in which we can add a Text, subtext, icon, and also a listener. The below code will be a complete code for MainActivity.java Activity. 

Java




public class MainActivity
    extends MaterialPreferenceActivity {
  
    @Override
    @NonNull
    protected MaterialPreferenceList
    getMaterialPreferenceList(@NonNull Context context)
    {
  
        MaterialPreferenceCard card
            = new MaterialPreferenceCard.Builder()
                  .title("Hello Geek")
                  .build();
        MaterialPreferenceCard card2
            = new MaterialPreferenceCard.Builder()
                  .title("Hello Geek")
                  .build();
        MaterialPreferenceCard card3
            = new MaterialPreferenceCard.Builder()
                  .title("Hello Geek")
                  .build();
  
        MaterialPreferenceCard.Builder cardBuilder
            = new MaterialPreferenceCard.Builder();
        cardBuilder.addItem(
            new MaterialPreferenceActionItem.Builder()
                .text("Material Preference Library")
                .subText("Sub text")
                .icon(R.mipmap.ic_launcher)
                .setOnClickAction(
                    new MaterialPreferenceItemOnClickAction() {
                        @Override public void onClick()
                        {
                            Toast
                                .makeText(
                                    context, "Item CLicked",
                                    Toast.LENGTH_SHORT)
                                .show();
                        }
                    })
                .build());
  
        card = cardBuilder.title("Item 1").build();
        card2 = cardBuilder.title("Item 2").build();
        card3 = cardBuilder.title("Item 3").build();
  
        return new MaterialPreferenceList.Builder()
            .addCard(card)
            .addCard(card2)
            .addCard(card3)
            .build();
    }
    @Override protected CharSequence getActivityTitle()
    {
        return "GFG Tutorial";
    }
}


In the above code we have added a few more Cards and used a new Card Item. As we can see we don’t have to worry about a single line of XML code. Don’t have to worry about Responsive layout, this library handles everything automatically. Also if we click the item, Toast is being shown because we have set it inside the onclickListener of each Item.

Final Output: 

Final Output

As we can see the output is is successfully executed . Now we know how to use the Material Preference Library



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads