Skip to content

Instantly share code, notes, and snippets.

@mgranberry
Created June 2, 2015 21:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save mgranberry/865ffda7e52e6b78e318 to your computer and use it in GitHub Desktop.
Save mgranberry/865ffda7e52e6b78e318 to your computer and use it in GitHub Desktop.
A set of Anko-compatible extensions for Google's Material Design Support Library
fun ViewManager.appBarLayout(init: AppBarLayout.() -> Unit = {}) =
__dslAddView({ AppBarLayout(it) }, init, this)
fun ViewManager.collapsingToolbarLayout(init: CollapsingToolbarLayout.() -> Unit = {}) =
__dslAddView({ CollapsingToolbarLayout(it) }, init, this)
fun ViewManager.coordinatorLayout(init: CoordinatorLayout.() -> Unit = {}) =
__dslAddView({ CoordinatorLayout(it) }, init, this)
fun ViewManager.floatingActionButton(init: FloatingActionButton.() -> Unit = {}) =
__dslAddView({ FloatingActionButton(it) }, init, this)
fun ViewManager.navigationView(init: NavigationView.() -> Unit = {}) =
__dslAddView({ NavigationView(it) }, init, this)
fun ViewManager.tabLayout(init: TabLayout.() -> Unit = {}) =
__dslAddView({ TabLayout(it) }, init, this)
fun ViewManager.textInputLayout(init: TextInputLayout.() -> Unit = {}) =
__dslAddView({ TextInputLayout(it) }, init, this)
fun View.snackbar(text: CharSequence, duration: Int = Snackbar.LENGTH_SHORT, init: Snackbar.() -> Unit = {}): Snackbar {
val snack = Snackbar.make(this, text, duration)
snack.init()
snack.show()
return snack
}
fun View.snackbar(text: Int, duration: Int = Snackbar.LENGTH_SHORT, init: Snackbar.() -> Unit = {}): Snackbar {
val snack = Snackbar.make(this, text, duration)
snack.init()
snack.show()
return snack
}
private object ViewCounter {
private var viewCounter = AtomicInteger(1)
public fun generateViewId(): Int {
while (true) {
val result = viewCounter.get()
// aapt-generated IDs have the high byte nonzero; clamp to the range under that.
var newValue = result + 1
if (newValue > 16777215) newValue = 1 // Roll over to 1, not 0.
if (viewCounter.compareAndSet(result, newValue)) {
return result
}
}
}
}
fun View.generateViewIdCompat(): Int {
if (android.os.Build.VERSION.SDK_INT >= 19)
return View.generateViewId()
else
return ViewCounter.generateViewId()
}
@nschwermann
Copy link

Thanks for putting this up

@sargunv
Copy link

sargunv commented Jul 28, 2015

I've forked this to add widgets from the v4 and v7 support libraries, and also snackbar extensions for activities and fragments: https://gist.github.com/sargunster/418c0fd98eb765fa9aca

@cnevinc
Copy link

cnevinc commented Nov 5, 2015

Thanks! I've updated it using ankoView instead.
https://gist.github.com/cnevinc/539d6659a4afbf6a0b08

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment