项目作者: Bryanx

项目描述 :
🍰 A tiny android annotation library for injecting styled attributes into custom views.
高级语言: Kotlin
项目地址: git://github.com/Bryanx/cakecutter.git
创建时间: 2020-03-24T17:47:59Z
项目社区:https://github.com/Bryanx/cakecutter

开源协议:Apache License 2.0

下载


🍰 CakeCutter

A tiny annotation library for injecting styled attributes into custom views.

Example

Traditional way of loading styled attributes:

  1. class CustomView(ctx: Context, attrs: AttributeSet) : FrameLayout(ctx, attrs) {
  2. var customText: String = ""
  3. var customNumber: Int = 0
  4. var customSize: Float = 0F
  5. init {
  6. val styledAttrs = ctx.obtainStyledAttributes(attrs, R.styleable.CustomView)
  7. try {
  8. customText = styledAttrs.getString(R.styleable.CustomView_customText) ?: customText
  9. customNumber = styledAttrs.getInt(R.styleable.CustomView_customNumber, customNumber)
  10. customSize = styledAttrs.getDimension(R.styleable.CustomView_customSize, customSize)
  11. } finally {
  12. styledAttrs.recycle()
  13. }
  14. }
  15. }

With cakecutter:

  1. class CustomView(ctx: Context, internal val attrs: AttributeSet) : FrameLayout(ctx, attrs) {
  2. @Styleable var customText: String = ""
  3. @Styleable var customNumber: Float = 0F
  4. @Styleable var customSize: Int = 0
  5. init {
  6. CakeCutter.bind(this)
  7. }
  8. }

The styleables are bound by property name.

Some advantages:

  • Default values are assigned once instead of twice.
  • Layout/programmatic setters are combined.
  • Less boilerplate.

Alternative annotation:

  1. @BindStyleable("customText") var otherTextName: String = ""

With this annotation the props can have different names than the styleables.

Generated code

It works similarly to Dagger and ButterKnife, here is the generated code for above example:

  1. fun bind(view: CustomView) {
  2. view.context.obtainStyledAttributes(view.attrs, R.styleable.CustomView)
  3. .apply {
  4. try {
  5. view.customText = getBoolean(6, view.customText)
  6. view.customNumber = getString(R.styleable.CustomView_customNumber) ?: view.customNumber
  7. view.customSize = getDimension(R.styleable.CustomView_customSize, view.customSize)
  8. } finally {
  9. recycle()
  10. }
  11. }
  12. }

Install

Add these dependencies in your app’s build.gradle file:

  1. implementation 'nl.bryanderidder.cakecutter:annotations:0.2.1'
  2. kapt 'nl.bryanderidder.cakecutter:compiler:0.2.1'

Use annotationProcessor instead of kapt for Java projects. \
For kotlin projects add this to the top of your build.gradle file if it’s not added yet:

  1. apply plugin: "kotlin-kapt"

After adding the annotations you have to rebuild the project to load the generated code.

Note

This project is more of an expirement/study on annotation libraries and ButterKnife.

At the moment this library does not support these custom attribute types:

  • Fraction types
  • Multi types




The cake is now ready to be served.

🍰