Findviewbyid kotlin ошибка

DEPRECATED

In Kotlin we can get the id of the view without the use of the findViewById syntax.

For example we are using the following the layout from that we will get the id of the view and perform operation

Layout

<?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

UPDATE

Now the kotlin-android-extensions is deprecated , instead of using the kotlin provided binding , we can use now the View-Binding and it works same as above solution, Just you need to use the below in your app gradle

android {
    ...
    buildFeatures {
        viewBinding true
    }
}

The «findViewById» method is an important part of the Android development process, as it allows you to access the view elements in your layout. However, sometimes when working with Kotlin, you may encounter an error that says «Type inference failed», preventing you from using the method. This error typically occurs because of issues with the types and casting of the view elements. To resolve this issue, there are a few different methods you can try.

Method 1: Use explicit type casting

To fix the «Not able to findViewById» error in Kotlin, you can use explicit type casting. This involves explicitly casting the view to the desired type.

Here is an example of how to do it:

val myView = findViewById<View>(R.id.my_view)
val myButton = myView as Button

In this example, we first retrieve the view using findViewById and cast it to a View. Then, we explicitly cast it to a Button.

If you are unsure about the type of the view, you can use the as? operator to safely cast it:

val myView = findViewById<View>(R.id.my_view)
val myButton = myView as? Button

This will return null if the view cannot be cast to a Button.

You can also use the findViewById extension function provided by the Kotlin Android Extensions plugin:

val myButton = findViewById<Button>(R.id.my_button)

This will automatically cast the view to a Button.

In summary, to fix the «Not able to findViewById» error in Kotlin, you can use explicit type casting or the findViewById extension function.

Method 2: Use the «as» operator to cast the view

If you’re getting a «Type inference failed» error when trying to find a view by ID in Kotlin, you can use the «as» operator to cast the view to the appropriate type. Here’s an example of how to do it:

val myButton = findViewById(R.id.my_button) as Button

In this example, we’re finding a view with the ID «my_button» and casting it to a Button type. This ensures that we can use all of the Button-specific methods and properties on the view.

If you’re not sure what type of view you’re dealing with, you can use the «is» operator to check before casting:

val myView = findViewById(R.id.my_view)
if (myView is Button) {
    // Cast to Button and use its methods and properties
    val myButton = myView as Button
    myButton.text = "Click me!"
} else {
    // Handle the case where myView is not a Button
}

In this example, we’re first checking if myView is a Button using the «is» operator. If it is, we can safely cast it to a Button and use its methods and properties. If it’s not a Button, we can handle that case appropriately.

Overall, using the «as» operator to cast views in Kotlin can help you avoid the «Type inference failed» error and ensure that you can use all of the methods and properties of the view you’re working with.

Method 3: Use the «lateinit» keyword for the view variable

If you are getting the «Type inference failed» error while trying to use findViewById in Kotlin for an Android app, you can use the lateinit keyword to solve the issue. Here is how to do it:

  1. Declare the view variable using the lateinit keyword:
private lateinit var myView: View
  1. Initialize the view variable in the onCreate method:
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    myView = findViewById(R.id.my_view)
}
  1. Use the view variable in your code:
myView.visibility = View.VISIBLE

By using the lateinit keyword, you are telling the compiler that you will initialize the variable later in the code. This way, you avoid the «Type inference failed» error and can use the findViewById method to get a reference to your view.

Note that you should only use lateinit for mutable variables that you will initialize later. If you try to use a lateinit variable before initializing it, you will get a lateinit exception.

Method 4: Use the «by lazy» delegate for the view

To fix the error «Type inference failed» when trying to use findViewById in Kotlin, you can use the by lazy delegate for the view. This delegate allows you to initialize the view only when it is accessed for the first time, which can avoid the type inference issue.

Here’s an example of how to use by lazy in your code:

private val myButton by lazy { findViewById<Button>(R.id.my_button) }

In this example, myButton is a property that is initialized using by lazy. The findViewById method is called inside the curly braces, and the type of the view is specified using the generic type parameter <Button>. The ID of the view is passed as an argument to findViewById.

You can then use myButton as if it were a regular view property:

myButton.setOnClickListener { /* do something */ }

By using by lazy, you can avoid the type inference issue and ensure that the view is only initialized when it is actually used in your code. This can improve performance and avoid potential bugs.

In summary, to fix the error «Type inference failed» when using findViewById in Kotlin, you can use the by lazy delegate for the view. Initialize the view inside the curly braces and specify the type using the generic type parameter. Then, use the property as if it were a regular view property.

Кажется, это самый простой способ избавиться от findViewById ()

Перейдите в свой Build.Gradle(модуль: приложение)

Добавьте следующую строку

apply plugin: 'kotlin-android-extensions'
  • Затем он попросит вас синхронизировать
  • Затем нажмите кнопку

После этого войдите в свой файл активности. Скажите, что это много MainActivity.kt

Там импорт
Импорт одного представления

import kotlinx.android.synthetic.main.<layout_name>.<view_name>;

или

Чтобы импортировать все представления

import kotlinx.android.synthetic.main.<layout_name>.*;

Пример:
в макете

<Checkbox id="@+/forwardBox" . .  . />

находится в макете activity_main
затем импортируйте как

import kotlinx.android.synthetic.main.activity_main.forwardBox;

поэтому либо в вашей функции, либо в классе используйте ее напрямую

forwardBox.isChecked = false

Problem Description:

I’m trying to use fragments to not burden my application with too many activities.
In my mainActivity there is a map, I then created a fragment where there are editText fields, I would like to use these editText to insert numbers to be used as parameters to pass to a function created in another class called navFun.
I tried to write the code but I don’t understand why I get these errors when using findViewById:

Unresolved reference: findViewById

this is my fragment code

package uk.co.lorenzopulcinelli.navigationdrawer

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import java.lang.Exception

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [CreatePathFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class CreatePathFragment : Fragment() {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null


    val mainActivity: MainActivity = MainActivity()
    val navFun: NavFun = NavFun(mainActivity.context, mainActivity.mapView)

    private lateinit var editTextLatitudineP1: EditText
    private lateinit var editTextLongitudineP1: EditText
    private lateinit var editTextLatitudineP2: EditText
    private lateinit var editTextLongitudineP2: EditText


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {



        // create path between editText points

        editTextLatitudineP1 = findViewById<EditText>(R.id.editTextLatitudineP1)
        editTextLongitudineP1 = findViewById<EditText>(R.id.editTextLongitudineP1)
        editTextLatitudineP2 = findViewById<EditText>(R.id.editTextLatitudineP2)
        editTextLongitudineP2 = findViewById<EditText>(R.id.editTextLongitudineP2)

        val b = findViewById<Button>(R.id.location)
        b.setOnClickListener{
            try {
               Log.d("Path", "Clicked")
               val p1lati: Double = editTextLatitudineP1.text.toString().toDouble()
               val p1long: Double = editTextLongitudineP1.text.toString().toDouble()
               val p2lati: Double = editTextLatitudineP2.text.toString().toDouble()
               val p2long: Double = editTextLongitudineP2.text.toString().toDouble()
               println("latitudine: $p2lati, longitudine: $p2long")
               navFun.routePath(p1lati, p1long, p2lati, p2long)
               mainActivity.mapView.invalidate()
            } catch (e: Exception) {
                Toast.makeText(context, "Error when entering coordinates", Toast.LENGTH_SHORT).show()
            }
        }

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_create_path, container, false)
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment CreatePathFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            CreatePathFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}

and this is my fragment xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context=".CreatePathFragment"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/crea_percorso"
        android:textColor="@color/black"
        android:textSize="40sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/inserisci_le_coordinate_dei_punti_tra_cui_vuoi_creare_un_percorso" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/latitudine_punto_di_partenza" />

    <EditText
        android:id="@+id/editTextLatitudineP1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:ems="10"
        android:hint="@string/latitudine_p1"
        android:inputType="numberSigned|numberDecimal" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/longitudine_punto_di_partenza" />

    <EditText
        android:id="@+id/editTextLongitudineP1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:ems="10"
        android:hint="@string/longitudine_p1"
        android:inputType="numberSigned|numberDecimal" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/latitudine_punto_di_arrivo" />

    <EditText
        android:id="@+id/editTextLatitudineP2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:ems="10"
        android:hint="@string/latitudine_p2"
        android:inputType="numberSigned|numberDecimal" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/longitudine_punto_di_arrivo" />

    <EditText
        android:id="@+id/editTextLongitudineP2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:ems="10"
        android:hint="@string/longitudine_p2"
        android:inputType="numberSigned|numberDecimal" />

    <Button
        android:id="@+id/location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/crea_percorso"
        />

</LinearLayout>

Solution – 1

    override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    val view = inflater.inflate(R.layout.fragment_create_path, container, false)

    // create path between editText points

    editTextLatitudineP1 = view.findViewById<EditText>(R.id.editTextLatitudineP1)
    editTextLongitudineP1 = view.findViewById<EditText>(R.id.editTextLongitudineP1)
    editTextLatitudineP2 = view.findViewById<EditText>(R.id.editTextLatitudineP2)
    editTextLongitudineP2 = view.findViewById<EditText>(R.id.editTextLongitudineP2)

    val b = findViewById<Button>(R.id.location)
    b.setOnClickListener{
        try {
           Log.d("Path", "Clicked")
           val p1lati: Double = editTextLatitudineP1.text.toString().toDouble()
           val p1long: Double = editTextLongitudineP1.text.toString().toDouble()
           val p2lati: Double = editTextLatitudineP2.text.toString().toDouble()
           val p2long: Double = editTextLongitudineP2.text.toString().toDouble()
           println("latitudine: $p2lati, longitudine: $p2long")
           navFun.routePath(p1lati, p1long, p2lati, p2long)
           mainActivity.mapView.invalidate()
        } catch (e: Exception) {
            Toast.makeText(context, "Error when entering coordinates", Toast.LENGTH_SHORT).show()
        }
    }

    // Inflate the layout for this fragment
    return view
}

You must create your view first and than call findViewById on that view.

Solution – 2

findViewById will not work inside onCreateView, because at that time the UI is being created, so the views are not initialized yet.

try to link the views inside onViewCreated instead. <– you can import it using ctrl+O

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
     
       editTextLatitudineP1 = findViewById<EditText>(R.id.editTextLatitudineP1)

       //.....the rest of your code
    }

I created a class (not MainActivity) that needs to write to an element in the activity_main.xml UI.

The element in question is declared as the following:

<ImageView
    android:id="@+id/beatBarRenderView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

All I’m trying to do is draw on the view by doing the following:

beatBarRenderView.background = BitmapDrawable(resources, bitmap)

The bitmap is correctly declared before this line.

The code seems to be able to find beatBarRenderView, because I don’t get any errors during compilation. However, during runtime, the program crashes and I get the following error:

Attempt to invoke virtual method ‘android.view.View android.view.Window.findViewById(int)’ on a null object reference

So what I tried to do is declare beatBarRenderView in this class manually by doing the following:

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

    beatBarRenderView = findViewByID(R.id.beatBarRenderView)
}

Now I get a compilation error:

Unresolved reference: findViewByID

Keep in mind that I’ve read similar questions on this site. I’ve added kotlin-android-extensions to build.gradle already. I think I imported the correct libraries (Android Studio doesn’t recommend any for the compilation error, it just tells me to create an abstract class). This worked in MainActivity and only broke when I moved it to another class file.

Понравилась статья? Поделить с друзьями:
  • Fltmgr file system windows 10 ошибка
  • Fls fuel level ошибка
  • Floating point exception ошибка ansys
  • Floating point exception fluent ошибка
  • Floating point division by zero ошибка при удалении