code

Adapter 또는 ViewHolder의 Kotlin 합성

codestyles 2020. 11. 11. 20:11
반응형

Adapter 또는 ViewHolder의 Kotlin 합성


저는 kotlin을 처음 사용합니다. findViewByIdActivity클래스 에서 성가신 메서드 대신 합성 메서드를 찾아서 사용하려고 시도했지만 "View (어댑터 클래스에서 유용)에서 합성 속성을 호출하려면 kotlinx.android.synthetic.main도 가져와야합니다. .전망.*." 하지만 정확히 어떻게 작동하는지 알 수 없습니까? 예가 있습니까?


https://github.com/antoniolg/Kotlin-for-Android-Developers의 간단한 예

import kotlinx.android.synthetic.item_forecast.view.*

class ForecastListAdapter() : RecyclerView.Adapter<ForecastListAdapter.ViewHolder>() {

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {

        fun bindForecast(forecast: Forecast) {
            itemView.date.text = forecast.date.toDateString()
        }
    }
}

쓸 필요가 없습니다

val view = itemView.findViewById(R.id.date) as TextView
view.text = forecast.date.toDateString()

다만

itemView.date.text = forecast.date.toDateString()

간단하고 효과적입니다!


Kotling 1.1.4 출력

추가 정보 : https://antonioleiva.com/kotlin-android-extensions/

따라서 build.gradle에 이것을 추가하여 활성화해야합니다 .

apply plugin: 'org.jetbrains.kotlin.android.extensions'
androidExtensions {
    experimental = true
}

이 새로운 버전의 Kotlin 이후 Android 확장 프로그램은 몇 가지 새로운 흥미로운 기능을 통합했습니다. 모든 클래스의 캐시 (흥미롭게도 ViewHolder 포함)

ViewHolder (또는 사용자 정의 클래스)에서 사용

class ViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), 
        LayoutContainer {

    fun bind(title: String) {
        itemTitle.text = "Hello Kotlin!"
    }
}

당신은 필요합니다

import kotlinx.android.synthetic.row_wall.view.*

그리고 나중에 다음과 같은 내용이 있습니다.

convertView.titleText.text = item.title

요점은 view. *가 View 클래스에 대한 확장을 도입한다는 것입니다.


시험

class CustomViewModel(val baseView: View) { val firstName = baseView.firstName val lastName = baseView.lastName }

뷰 객체는 뷰 참조를 노출합니다 : https://discuss.kotlinlang.org/t/unable-to-use-kotlin-android-extension-in-adapter-class/2890


최신 버전 l ;.을 사용하는 경우 실험적 = true를 추가 할 필요가 없습니다.

프로젝트 수준 Gradle

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

그리고 앱 수준 Gradle에서

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

그리고 의존성 ..

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

아래로 가져 오기

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

및 예

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

class AnimalVH(parent: ViewGroup, layoutID: Int) : BaseViewHolder<Animal>(parent, layoutID) {

    override fun bindData(animal: Animal) {
        itemView.tv_animal.text = animal.title
    }
}

BaseViewHolder는

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

이는 소스 파일의 시작 부분에 다음 줄을 배치해야 함을 의미합니다.

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

So now instead of, for example, findView(R.id.textView) as TextView you would write just textView. The latter is a synthetic extension property located in the package kotlinx.android.synthetic.main.view, that's why you have to import everything from it.

There's a tutorial on the official site, take a look.


FYI: Data binding is recommended over synthetic for view lookups.

Comment from a DA for Android from Google on Reddit

Hey! Developer Advocate for Android at Google here!

I wanted to add a bit of background here. Kotlin Extensions with synthetic views was never intentionally “recommended” though that shouldn’t be taken as a recommendation to not use them. If they're working for you please feel free to continue using them in your app!

We’ve been shifting away from them (e.g. we don’t teach them in the Udacity course) because they expose a global namespace of ids that’s unrelated to the layout that’s actually inflated with no checks against invalid lookups, are Kotlin only, and don't expose nullability when views are only present in some configuration. All together, these issues cause the API to increase number of crashes for Android apps.

On the other hand, they do offer a lightweight API that can help simplify view lookups. In this space it's also worth taking a look at Data Binding which also does automatic view lookups - as well as integrates with LiveData to automatically update your views as data changes.

Today, there's a few options in this space that work:

Data Binding is the recommendation for view lookup as well as binding, but it does add a bit of overhead when compared to Android Kotlin Extensions. It's worth taking a look to see if this is a good fit for your app. Data Binding also allows you to observe LiveData to bind views automatically when data changes. Compared to Kotlin Extensions, it adds compile time checking of view lookups and type safety. Android Kotlin Extensions is not officially recommended (which is not the same as recommendation against). It does come with the issues mentioned above, so for our code we're not using them. Butter Knife is another solution that is extremely popular and works for both Kotlin and the Java Programming Language. Reading through the comments here there's a lot of developers that are having great luck with Kotlin Extensions. That's great - and something we'll keep in mind as we look at ways to continue improving our APIs. If you haven't taken a look at Data Binding, definitely give it a shot.

As an aside, our internal code style guide is not intended to be directly applied outside of our codebase. For example, we use mPrefixVariables, but there's no reason that every app should follow that style.

참고URL : https://stackoverflow.com/questions/33304570/kotlin-synthetic-in-adapter-or-viewholder

반응형