All Downloads are FREE. Search and download functionalities are using the official Maven repository.

butterknife.plugin.FinalRClassBuilder.kt Maven / Gradle / Ivy

There is a newer version: 10.2.3
Show newest version
package butterknife.plugin

import com.squareup.javapoet.ClassName
import com.squareup.javapoet.FieldSpec
import com.squareup.javapoet.JavaFile
import com.squareup.javapoet.TypeSpec
import javax.lang.model.element.Modifier.FINAL
import javax.lang.model.element.Modifier.PUBLIC
import javax.lang.model.element.Modifier.STATIC


private const val ANNOTATION_PACKAGE = "androidx.annotation"
private const val ANNOTATION_PACKAGE_LEGACY = "android.support.annotation"
internal val SUPPORTED_TYPES = setOf("anim", "array", "attr", "bool", "color", "dimen",
    "drawable", "id", "integer", "layout", "menu", "plurals", "string", "style", "styleable")

/**
 * Generates a class that contains all supported field names in an R file as final values.
 * Also enables adding support annotations to indicate the type of resource for every field.
 */
class FinalRClassBuilder(
  private val packageName: String,
  private val className: String,
  private val useLegacyTypes: Boolean
) {

  private var resourceTypes = mutableMapOf()

  fun build(): JavaFile {
    val result = TypeSpec.classBuilder(className)
        .addModifiers(PUBLIC, FINAL)
    for (type in SUPPORTED_TYPES) {
      resourceTypes.get(type)?.let {
        result.addType(it.build())
      }
    }
    return JavaFile.builder(packageName, result.build())
        .addFileComment("Generated code from Butter Knife gradle plugin. Do not modify!")
        .build()
  }

  fun addResourceField(type: String, fieldName: String, fieldValue: String) {
    if (type !in SUPPORTED_TYPES) {
      return
    }
    val fieldSpecBuilder = FieldSpec.builder(Int::class.javaPrimitiveType, fieldName)
        .addModifiers(PUBLIC, STATIC, FINAL)
        .initializer(fieldValue)

    fieldSpecBuilder.addAnnotation(getSupportAnnotationClass(type))

    val resourceType =
        resourceTypes.getOrPut(type) {
          TypeSpec.classBuilder(type).addModifiers(PUBLIC, STATIC, FINAL)
        }
    resourceType.addField(fieldSpecBuilder.build())
  }

  private fun getSupportAnnotationClass(type: String): ClassName {
    val supportPackage = if (useLegacyTypes) ANNOTATION_PACKAGE_LEGACY else ANNOTATION_PACKAGE
    return ClassName.get(supportPackage, type.capitalize() + "Res")
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy