eygraber
03/24/2017, 1:03 AMAnkoInternals.wrapContextIfNeeded
doesn't always work (e.g. I pass Widget.AppCompat.Button.Borderless
and instead of a flat button, I get a raised button with certain flat button attributes).
I've worked around it for now by declaring my own version of ViewManager.ankoView
, but it's annoying to either have a generic function (themedView
) or make a function for every View
that I would want it for:
inline fun <reified T : View> ViewManager.themedView(theme: Int, init: T.() -> Unit): T {
val ctx = AnkoInternals.wrapContextIfNeeded(AnkoInternals.getContext(this), theme)
val view = initiateView(ctx, T::class.java, theme)
view.init()
AnkoInternals.addView(this, view)
return view
}
fun <T : View> initiateView(ctx: Context, viewClass: Class<T>, theme: Int): T {
fun getConstructor() = viewClass.getConstructor(Context::class.java, AttributeSet::class.java, Int::class.java, Int::class.java)
fun getConstructor2() = viewClass.getConstructor(Context::class.java)
fun getConstructor3() = viewClass.getConstructor(Context::class.java, AttributeSet::class.java)
return try {
getConstructor().newInstance(ctx, null, 0, theme)
} catch (e: NoSuchMethodException) {
try {
getConstructor2().newInstance(ctx)
}
catch (e: NoSuchMethodException) {
try {
getConstructor3().newInstance(ctx, null)
}
catch (e: NoSuchMethodException) {
throw AnkoException("Can't initiate View of class ${viewClass.name}: can't find proper constructor")
}
}
}
}
david.bilik
03/24/2017, 5:07 AM