Code Monkey home page Code Monkey logo

materialdrawerkt's Introduction

MaterialDrawerKt

Build Status Bintray Awesome Kotlin Badge Android Arsenal

Create navigation drawers in your Activities and Fragments without having to write any XML, in pure Kotlin code, with access to all the features of the original library: all sorts of menu items, badges, account headers, and more.

This library is a Kotlin DSL wrapper around the mikepenz/MaterialDrawer library, and features:

  • Access to all of the original library's features with a nice, concise API
  • Fixes for the couple of inconsistencies of the original API
  • Detailed code comments for conveninent in-IDE documentation lookup (Ctrl+Q on Windows, โŒƒJ on Mac)

Sample app

You can find the sample app in the Play Store, and its source code in the app module of the project.

Setup

The library is hosted on mavenCentral(). To use it, add the following to your module level build.gradle file's dependencies:

implementation 'co.zsmb:materialdrawer-kt:3.0.0'

// required support lib modules
implementation "androidx.appcompat:appcompat:${versions.appcompat}"
implementation "androidx.recyclerview:recyclerview:${versions.recyclerView}"
implementation "androidx.annotation:annotation:${versions.annotation}"
implementation "com.google.android.material:material:${versions.material}"
implementation "androidx.constraintlayout:constraintlayout:${versions.constraintLayout}"

In general, you don't have to include the original library separately. (See the note in the FAQ.)

If you want to use the pre-Kotlin version of the base library for some reason, you can use the last 2.x release of the library found here.

If you're not using AndroidX yet, you can use the last 1.x release of the library found here.

Basic usage

Just as a general note, try using the in-IDE documentation when you're in doubt about anything. It's much more detailed than the original library's docs, this was one of the design goals of the library. The IntelliJ/Android Studio shortcut for bringing up the docs about a function is Ctrl+Q on Windows, and โŒƒJ on Mac.

To add a navigation drawer, you just have to add the following to your Activity's onCreate function:

drawer {}

This will give you an empty sheet that you can drag in from the left side of the screen. You can add menu items to it like this:

drawer {
    primaryItem("Home") {}
    divider {}
    primaryItem("Users") {}
    secondaryItem("Settings") {}
}

For all the available types of menu items, see the "Drawer item types" in the sample app.

You can modify properties of the drawer inside the drawer {} block, and properties of the menu items in their respective blocks:

drawer {
    headerViewRes = R.layout.header
    closeOnClick = false
    
    primaryItem("Home") {
        icon = R.drawable.ic_home
    }
    divider {}
    primaryItem("Users") {
        icon = R.drawable.ic_user
    }
    secondaryItem("Settings") {
        icon = R.drawable.ic_settings
        selectable = false
    }
}

Note that most of these properties are non-readable, and can only be used for setting these values. This is why these properties are marked as deprecated, and will cause build errors. The rest should be safe to use to read back any values you've set, if you had to do that for whatever reason.

For a complete reference of the wrapper methods and properties, see the list in the wiki.

Advanced features

Account headers

Creating an account header with profile entries can be done like so:

drawer {
    accountHeader { 
        profile("Samantha", "[email protected]") {
            icon = "http://some.site/samantha.png"
        }
        profile("Laura", "[email protected]") { 
            icon = R.drawable.profile_laura
        }
    }
    
    primaryItem("Home")
}

Note that loading images from URLs requires additional setup, see the Image loading section of this document or the DrawerApplication class in the sample app for guidance.

Footers

You can add items to an always visible, sticky footer in by nesting them inside a footer block:

drawer {
    footer {
        primaryItem("Primary item")
        secondaryItem("Secondary item")
    }
}

Listeners

Listeners can be added to both individual drawer items and the entire drawer. Some examples:

drawer {
    primaryItem("Item 1")
    primaryItem("Item 2") {
        // Called only when this item is clicked
        onClick { _ ->
            Log.d("DRAWER", "Click.")
            false
        }
    }

    // Called when any drawer item is clicked
    onItemClick { _, position, _ ->
        Log.d("DRAWER", "Item $position clicked")
        false
    }
    
    onOpened { 
        Log.d("DRAWER", "Navigation drawer opened")
    }
}

More examples in the "Listeners" section of the sample app.

Badges

Add badges to drawer items, and customize them with this syntax:

drawer {
    primaryItem {
        badge("111") {
            cornersDp = 0
            color = 0xFF0099FF
            colorPressed = 0xFFCC99FF
        }
    }
}

You can see more examples in the "Badges" section of the sample app.

Conversion from original

This is a rough guide to how the original API's features are converted to the DSL, for those who are already familiar with the original library.

Builders

Builders are replaced by functions that are named without the "Builder" suffix.

DrawerBuilder()
    .withActivity(this)
    .build()

... is replaced with ...

drawer { 

}

DrawerItems

Calls to XyzDrawerItem classes are replaced with functions as well. The "Drawer" word is omitted from the function's name. Note that properties like names and descriptions of the drawer items become parameters of these functions.

For example:

PrimaryDrawerItem().withName("Item name")

... is replaced with ...

primaryItem("Item name") {

}

with functions

Calls to .withXyz() functions are replaced with properties that you can set. For a complete reference of the wrapper methods and properties, see the list in the wiki.

Very few of these are readable. If you want to read these at build time for some reason, check the documentation. Non-readable properties should be deprecated and not compile, but if they do, they will throw a NonReadablePropertyException if you attempt to read their value.

For an example...

AccountHeaderBuilder()
    .withActivity(this)
    .withHeaderBackground(R.color.colorPrimary)
    .build()

... is replaced with ...

accountHeader {
    headerBackgroundRes = R.color.colorPrimary 
}

Note that overloaded functions are replaced with multiple properties, distinguished by suffixes. For example, the above withHeaderBackground function's three overloads can be set through the following properties:

Parameter type Property name
Int headerBackground
headerBackgroundRes
Drawable headerBackgroundDrawable
ImageHolder headerBackgroundImage

There may be defaults without suffixes for what's assumed to be the most popular use case.

Listeners

Adding simple listeners to drawers (or individual drawer items) are done with onXyz function calls, which take lambdas as parameters. For example:

DrawerBuilder()
        .withActivity(this)
        .withOnDrawerItemClickListener(object : Drawer.OnDrawerItemClickListener {
            override fun onItemClick(view: View, position: Int, drawerItem: IDrawerItem<out Any?, out RecyclerView.ViewHolder>?): Boolean {
                Log.d("DRAWER", "Clicked!")
                return true
            }
        })
        .build()

... is replaced with ...

drawer {
    onItemClick { view, position, drawerItem -> 
        Log.d("DRAWER", "Clicked!")
        true
    }
}

Complex listeners

Listeners that originally have multiple callbacks have been broken up into individual functions:

DrawerBuilder()
        .withActivity(this)
        .withOnDrawerListener(object : Drawer.OnDrawerListener {
            override fun onDrawerSlide(drawerView: View?, slideOffset: Float) {
                Log.d("DRAWER", "Sliding")
            }

            override fun onDrawerClosed(drawerView: View?) {
                Log.d("DRAWER", "Closed")
            }

            override fun onDrawerOpened(drawerView: View?) {
                Log.d("DRAWER", "Opened")
            }
        })
        .build()

... is replaced with ...

drawer { 
    onSlide { _, _ ->
        Log.d("DRAWER", "Sliding")
    }
    onClosed {
        Log.d("DRAWER", "Closed")
    }
    onOpened {
        Log.d("DRAWER", "Opened")
    }
}

Image loading

Since the MaterialDrawer library doesn't include its own image loading solution, you have to set one up yourself. You have to do this before the first time MaterialDrawer has to load an image, for example, in your Application's onCreate method.

With the original library, this setup looks like this (Picasso is just used as an example):

DrawerImageLoader.init(object: AbstractDrawerImageLoader() {
    override fun placeholder(ctx: Context, tag: String?): Drawable {
        return DrawerUIUtils.getPlaceHolder(ctx)
    }

    override fun set(imageView: ImageView, uri: Uri, placeholder: Drawable?, tag: String?) {
        Picasso.with(imageView.context)
                .load(uri)
                .placeholder(placeholder)
                .into(imageView)
    }

    override fun cancel(imageView: ImageView) {
        Picasso.with(imageView.context)
                .cancelRequest(imageView)
    }
})

This can be replaced by the following:

drawerImageLoader {
    placeholder { ctx, tag ->
        DrawerUIUtils.getPlaceHolder(ctx)
    }
    set { imageView, uri, placeholder, tag ->
        Picasso.with(imageView.context)
                .load(uri)
                .placeholder(placeholder)
                .into(imageView)
    }
    cancel { imageView ->
        Picasso.with(imageView.context)
                .cancelRequest(imageView)
    }
}

FAQ

I want to use features of the base library that haven't made it to this one yet

If the base library gets features and they aren't ported to this wrapper yet, you can include that as a dependency in addition to this one, and use the two together. For these purposes, the internal DrawerBuilder that this library uses is exposed through a property, and you can access it like so:

drawer {
    builder.withKeepStickyItemsVisible(true)
}

The internal AccountHeaderBuilder is exposed in the same way:

accountHeader {
    builder.withHeightDp(20)
}

As for drawer items, you can just use the original API's calls on the items that are returned:

val item = primaryItem("Hello") {
    icon = R.drawable.profile
}
item.withBadge("10")
primaryItem("Hello") {
    icon = R.drawable.profile
}.withBadge("10")

License

Copyright 2020 Marton Braun

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.

materialdrawerkt's People

Contributors

rubengees avatar zsmb13 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

materialdrawerkt's Issues

Builder object doesn't seem to be accessible?

The FAQ states the following:

I want to use features of the base library that haven't made it to this one yet

If the base library gets features and they aren't ported to this wrapper yet, you can include that as a dependency in addition to this one, and use the two together. For these purposes, the internal DrawerBuilder that this library uses is exposed through a property, and you can access it like so:

drawer {
builder.withKeepStickyItemsVisible(true)
}

However, I get the following error when trying to do this in Android Studio:

screen shot 2018-06-12 at 11 20 00

What am I doing wrong? ๐Ÿ˜„

Using mikepenz/AboutLibraries with this lib causes issues while assembling the app.

Hello,

I was using the mikepenz/AboutLibraries lib version 5.9.7 with the java implementation of material drawer.

When I tried to added the kotlin wrapper (this library) it worked while testing, but when trying to assemble the app, I have these warning that make my build fail.

Warning: com.mikepenz.aboutlibraries.LibsBuilder: can't find referenced method 'com.mikepenz.fastadapter.AbstractAdapter wrap(com.mikepenz.fastadapter.FastAdapter)' in program class com.mikepenz.fastadapter.adapters.ItemAdapter
Warning: com.mikepenz.aboutlibraries.LibsBuilder: can't find referenced method 'com.mikepenz.fastadapter.adapters.ItemAdapter add(java.util.List)' in program class com.mikepenz.fastadapter.adapters.ItemAdapter
Warning: com.mikepenz.aboutlibraries.LibsFragmentCompat: can't find referenced method 'com.mikepenz.fastadapter.AbstractAdapter wrap(com.mikepenz.fastadapter.FastAdapter)' in program class com.mikepenz.fastadapter.adapters.ItemAdapter
Warning: com.mikepenz.aboutlibraries.LibsFragmentCompat: can't find referenced method 'com.mikepenz.fastadapter.adapters.ItemAdapter add(com.mikepenz.fastadapter.IItem[])' in program class com.mikepenz.fastadapter.adapters.ItemAdapter
Warning: com.mikepenz.aboutlibraries.LibsFragmentCompat$LibraryTask: can't find referenced method 'com.mikepenz.fastadapter.adapters.ItemAdapter clear()' in program class com.mikepenz.fastadapter.adapters.ItemAdapter
Warning: com.mikepenz.aboutlibraries.LibsFragmentCompat$LibraryTask: can't find referenced method 'com.mikepenz.fastadapter.adapters.ItemAdapter add(com.mikepenz.fastadapter.IItem[])' in program class com.mikepenz.fastadapter.adapters.ItemAdapter
Warning: com.mikepenz.aboutlibraries.LibsFragmentCompat$LibraryTask: can't find referenced method 'com.mikepenz.fastadapter.adapters.ItemAdapter add(java.util.List)' in program class com.mikepenz.fastadapter.adapters.ItemAdapter

Updating to the newer version of AboutLibraries causes other issues, but as they seem related to the AboutLibrary so I reported the issue on the lib issue tracker.

Is there a way to fix this ?

Thanks!

Add resource annotations

This is something that's included (at least in parts) in the base library, and it would be nice to have here.

This issue will have to be dealt with once Android Studio 3.0 is stable, since as of Canary 9, checks for these annotations don't seem to work when calling the annotated methods from Kotlin.

  • Update: Android Studio 3 is now stable, but the issue still remains, misusing properties that have these annotations doesn't produce any lint warnings.

  • Update 2: here is an unanswered StackOverflow issue for the same problem.


Example of what needs to be done:

var background: Int
    @Deprecated(...)
    get() = nonReadable()
    set(@DrawableRes value) { // <- resource annotation
        builder.withHeaderBackground(value)
    }

Example of what Studio should mark as an error:

accountHeader {
    background = R.drawable.header // this is ok, this is the proper usage
    background = 1234 // should warn for this, but doesn't
}

Example of what Studio marks as a warning in Java as of 3.0 Canary 9:

AccountHeaderBuilderKt builder = new AccountHeaderBuilderKt(this);
builder.setBackground(25124); // Error: Expected resource of type drawable

[Question] Color input as long

Is there a reason why some of the color arguments are held as a Long rather than an Int? Is it mainly to distinguish it from res attributes? Because in the end, colors are indeed ints, and right now I'm converting them with toLong() only to have them converted back

Getting null on actionBarDrawerToggle

Hi I am getting result.actionBarDrawerToggle must not be null. when I set .isDrawerIndicatorEnabled = true

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)


        initViews()
        getAuthToken()

        initDrawer(savedInstanceState)

        result = drawer {
            savedInstance = savedInstanceState

            toolbar = this@MainActivity.toolbar
            translucentStatusBar = false

            buildViewOnly = true
            generateMiniDrawer = true

            showOnFirstLaunch = true

            headerResult = accountHeader {
                selectionListEnabledForSingleProfile = false

                savedInstance = savedInstanceState
                translucentStatusBar = false
                background = R.drawable.header_bg

                mProfile = profile(App.prefs.firstName + " " + App.prefs.lastName, App.prefs.authEmail) {
                    iconUri = Helper.drawableToUri(this@MainActivity, R.mipmap.ic_launcher_circle)
                }

                profileSetting("Logout") {
                    iicon = GoogleMaterial.Icon.gmd_exit_to_app
                    onClick { _ ->
                        logout()
                        false
                    }
                }
            }

            sectionHeader("Available Tools")

            ToolsDataService.tools.forEach {
                primaryItem(it.name) {
                    icon = it.menuResource
                    onClick { _ ->
                        startActivity(Intent(this@MainActivity, it.activity))
                        true
                    }
                }
            }

            divider()

            actionBarDrawerToggleAnimated = true
            actionBarDrawerToggleEnabled = true
        }

        supportActionBar!!.setDisplayHomeAsUpEnabled(false)
        result.actionBarDrawerToggle.isDrawerIndicatorEnabled = true



        val miniResult = result.miniDrawer
        val firstWidth = UIUtils.convertDpToPixel(300f, this).toInt()
        val secondWidth = UIUtils.convertDpToPixel(72f, this).toInt()
        // Create and build our CrossFader
        val crossFader = Crossfader<CrossFadeSlidingPaneLayout>()
                .withContent(cross_fader)
                .withFirst(result.slider, firstWidth)
                .withSecond(miniResult.build(this), secondWidth)
                .withSavedInstance(savedInstanceState)
                .build()


        miniResult.withCrossFader(CrossfadeWrapper(crossFader))

        // Define a shadow (this is only for normal LTR layouts, if you have a RTL app you need to define the other one)
        crossFader.getCrossFadeSlidingPaneLayout().setShadowResourceLeft(R.drawable.material_drawer_shadow_left)

Switch item onClick listeners not called

I'd like to launch a fragment when the text of a switch item is clicked (and toggle the switch when the switch itself is clicked). However, it seems that when the item is bound the click listener set here is overridden.

switchItem {"Switch 1"
    selectable = true
    onClick { view ->
        Log.d("Drawer", "Clicked!")
        false
    }
}
switchItem {"Switch 2"
    selectable = false
    onClick { item ->
        Log.d("Drawer", "Clicked!")
        false
    }
}

The onClick function is not called in either of these cases. It seems there was an old issue that suggests it is possible, but I'm not sure how to do it. Any ideas?
mikepenz/MaterialDrawer#321

I can't set onclicklistener after init drawer

Code:

    fun ifLogged() {
        if (UserManager.isLogged()) {
            accountDrawer.withIcon(R.drawable.ic_sync_green_24dp)
            accountDrawer.withOnDrawerItemClickListener{ _ ->
                println("TEST")
            }
        } else {
            accountDrawer.withIcon(R.drawable.ic_sync_red_24dp)
        }
    }

Code:

            accountDrawer = secondaryItem(R.string.account) {
                selectable = true
            }

Problem:
zrzut ekranu z 2017-12-08 15-51-17

Add/Remove after initialize

How add/Remove items after initialize using KtLib??
Has issues talk ifself but no found Drawer.Result as explained in issue i read.

I try using this form
mDrawer.addItem( mPrimaryItem )

Sorry my english and Thanks for Lib.

Loading URL for AccountHeaderBackground

Hello,

I am looking for guidance and best practice in regards to using a URL based image as the Account Header Background photo.

Ultimate Goal: User will be able to update their profile photo AND the header background photo.

I am using Picasso as my image handling library, and was successful with the profile photo since it has the "iconURL" parameter.

I was hoping there would be a "backgroundURL" paramenter, but only found "background" and "backgroundDrawable" in the source.

The best method I have so far is as follows:

  1. Copy the existing header layout file, and reference the the new customViewRes in the header
    Example:
accountHeader {
                customViewRes = R.layout.header
                background = R.drawable.header

                selectionListEnabledForSingleProfile = false

                profile(userName, userEmail) {
                    iconUrl = profileURL
                }
            }
  1. Using picasso, set the target as the easily accessible ImageView called "material_drawer_account_header_background"
    The ImageView Reference above is thanks to Kotlin Extensions
Picasso.with(this@HomeActivity).load(headerURL).into(material_drawer_account_header_background)

My problem with this method is that I cannot reference the "material_drawer_account_header_background" imageview until the entire activity has loaded. Meaning that even after the drawer is built, the header layout seems to be null. The above Picasso code seems to only find the ImageView if I assign it to a button. With that said, I have also attempted to run the Picasso code in onResume to the same result.

Any advice and guidance would be appreciated!

How to get rid of the switch icon

I am trying to align the profile account header (picture, email, name) to the center and I am not able to get rid of the switch icon that is on the right. Since I am using a custom view, Every time I try to delete a view, it throws an exception since It can't find it.

Is there a way to have more control of how the profile account header is drawn?

actionBarDrawerToggle expecting ActionBarDrawerToggle instead of Boolean

Not sure if this is an actual bug but the original library has the following code:

new DrawerBuilder()
	.withActivity(this)
	.withTranslucentStatusBar(false)
        .withActionBarDrawerToggle(false)
	.addDrawerItems(
		//pass your items here
	)
	.build();

The following code complains about type mismatch:

result = drawer {
            translucentStatusBar = false
            actionBarDrawerToggle = false
            primaryItem("Home") {}
            primaryItem("Users") {}
            secondaryItem("Settings") {}
        }

What am I doing wrong?

Inline lambdas

This is an improvement that will have to wait until Kotlin 1.2 becomes stable, since we need default arguments for function types in inline methods, which is supposed to ship with that release.

Some implementation notes for later:

  • Make sure to measure performance difference of current vs inlined lambdas in the builders
  • Use the PublishedAPI annotation to keep currently internal methods internal

Update the dependencies

It may also be worthwhile to have the user include the original dependency anyways since they can update it directly while still using your bindings rather than wait for you to update the lib with the newer material drawer version.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.