Is there any easy way to get Anko to use theming c...
# anko
e
Is there any easy way to get Anko to use theming constructors on API 21+ The trick that is in place now with
AnkoInternals.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:
Copy code
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")
      }
    }
  }
}
d
There is no other way, the core is that with xml, AppCompat layoutInflater replace Button with AppcompatButton and so on with every other view. Now you dont have inflater and every view instance is created by you. I solved this by declaring appcompat* widgets