Programing

Kotlin에서 'findViewById'를 사용할 수 없습니다.

lottogame 2020. 11. 1. 17:15
반응형

Kotlin에서 'findViewById'를 사용할 수 없습니다. "유형 추론 실패"오류가 발생합니다.


RecycleViewby id 를 찾으려고하면 다음과 같은 오류가 발생 합니다.

오류 :- 유형 추론 실패 : 매개 변수 T 를 추론하기에 정보가 충분하지 않습니다.

오류

암호:

class FirstRecycleViewExample : AppCompatActivity() {
    val data = arrayListOf<String>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.first_recycleview)

        val recycler_view =  findViewById(R.id.recycler_view) as RecyclerView ///IN THIS LINE I AM GETTING THE ERROR

        data.add("First Data")
        data.add("Second Data")
        data.add("Third Data")
        data.add("Forth Data")
        data.add("Fifth Data")

        //creating our adapter
        val adapter = CustomRecycleAdapter(data)

        //now adding the adapter to recyclerview
        recycler_view.adapter = adapter
    }
}

다음과 같이 시도하십시오.

val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)

당신 Kotlin Android Extensions도 그것을 위해 사용할 수 있습니다 . 여기 에서 문서를 확인 하십시오 .
이를 recycler_view통해 코드에서 직접 호출 할 수 있습니다 .

Kotlin Android 확장 :

  • 앱에서 gradle.build추가apply plugin: 'kotlin-android-extensions'
  • 클래스 import kotlinx.android.synthetic.main.<layout>.*에서 <layout>레이아웃의 파일 이름이 어디에 있는지 가져 오기를 추가 하십시오.
  • 그게 전부 recycler_view입니다. 코드에서 직접 호출 할 수 있습니다 .

어떻게 작동합니까? 처음 호출 recycler_view하면에 대한 호출 findViewById이 수행되고 캐시 됩니다.


이제의 반환 유형이 대신 findViewById일반 이므로 유추 할 수 있는 API 수준 26에 있습니다. 여기 에서 관련 변경 로그를 볼 수 있습니다 .TView

따라서 다음을 수행 할 수 있어야합니다.

val recycler_view = findViewById<RecyclerView>(R.id.recycler_view)

아니면 이거:

val recycler_view: RecyclerView = findViewById(R.id.recycler_view)

일반적으로 Kotlin은 괄호 안에 제공된 정보를 사용하여 유형을 추론 할 수 있습니다.

이 경우에는 그렇게 할 수 없으므로 다음과 같이 명시 적으로 지정해야합니다.

findViewById<RecyclerView>(R.id.recycler_view)

유형에 대해서는 확실하지 않지만 그렇게 지정해야합니다.

Anko를 사용 하여 다음과 같이 코드를 더욱 단순화 할 수 있습니다.

val recycler_view : RecyclerView =  find(R.id.recycler_view)

에서 Kotlin우리의 사용하지 않고 뷰의 ID를 얻을 수 있습니다 findViewById구문.

예를 들어 다음 레이아웃을 사용하여 뷰의 ID를 가져오고 작업을 수행합니다.

형세

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/welcomeMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Hello World!"/>

</FrameLayout>

We are able to find the id of the view by using the following code

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    welcomeMessage.text = "Hello Kotlin!" ////WE ARE GETTING THE IDS WITHOUT USING THE FINDVIEWBYID syntax
}

HOW?

To be able to use it, you need an special import (the one I write below), but the IDE is able to auto-import it. Couldn’t be easier!

import kotlinx.android.synthetic.main.YOUR_LAYOUT_NAME.*/// HERE "YOUR_LAYOUT_NAME" IS YOUR LAYOUT NAME WHICH U HAVE INFLATED IN onCreate()/onCreateView() 

We need to import this property to get the id of the view without the use of the findviewbyid syntax.

For more information on this topic than please refer this link :- Click here


Add this line for your code as Whatever you are using controller.

val tvHello = findViewById<TextView>(R.id.tvHello)

Try this:

Here bind generic function use to bind view. its general function it's can use for any view.

class MyActivity : AppCompatActivity() {
    private lateinit var recycler_view : RecyclerView
    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        recycler_view = bind(R.id.recycler_view)
    }
}

fun <T : View> Activity.bind(@IdRes res : Int) : T {
    @Suppress("UNCHECKED_CAST")    
    return findViewById(res) as T
}

You can ignore giving ids to variables in kotlin. You just need to use a plugin

Paste this in your gradle

 apply plugin: 'kotlin-android-extensions'

and then you don't need to assign ids to var, you can just do it like

 recycler_view.setAdapter(youradapter);

Code: Another way to do it.

class KotlinActivity : AppCompatActivity() {


        var recycler_view: RecyclerView? = null

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_kotlin)

            recycler_view = findViewById<RecyclerView>(R.id.recycler_view)


        }
    }

보기로 작업을 수행하기 위해 개체를 만들 필요조차 없습니다. ID를 사용할 수 있습니다. 예 : Kotlin

recycle_view.adapter = adapter

Java 와 동일

RecycleView recycle_view = (RecycleView) findViewById(recycle_view);
recycle_view.setAdapter(adapter);

참고 URL : https://stackoverflow.com/questions/44950401/not-able-to-findviewbyid-in-kotlin-getting-error-type-inference-failed

반응형