Kotlin synthetic in Adapter or ViewHolder

前端 未结 7 645
孤独总比滥情好
孤独总比滥情好 2020-12-13 05:36

I am new in kotlin. I have found and tried to use synthetic method instead of annoying method findViewById in my Activity class, but I have found \

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-13 05:55

    If you are using the latest version l;.you don't have to add experimental = true to it.

    in Project level Gradle

    classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.21'
    

    And in app level Gradle

    apply plugin: 'kotlin-android'
    apply plugin: 'kotlin-android-extensions' //These should be on the top of file.
    

    and in dependencies..

    implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.21'
    

    and import below as

    import kotlinx.android.synthetic.main.your_layout_file_name.view.*
    

    and example

    import kotlinx.android.synthetic.main.item_animal.view.*
    
    class AnimalVH(parent: ViewGroup, layoutID: Int) : BaseViewHolder(parent, layoutID) {
    
        override fun bindData(animal: Animal) {
            itemView.tv_animal.text = animal.title
        }
    }
    

    where BaseViewHolder is

    abstract class BaseViewHolder(parent: ViewGroup, layoutID: Int) : RecyclerView.ViewHolder(
        LayoutInflater.from(parent.context).inflate(layoutID, parent, false)
    ) {
        abstract fun bindData(model: T)
    }
    

提交回复
热议问题