Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin-Android First App Unresolved Reference TextView Button etc

I'm new to Android & Kotlin development.

I wanted to get started with a simple "Hello World", but am already running into problems.

I added a Textview to my MainActivity and want to set an onClick listener to change the text of a TextView I dragged into the activity.

The compiler is now complaining that 'TextView' is an unresolved reference (it does the same with Buttons etc.).

I then added a kotlinx import as suggested by a website, but this fails to solve anything. Code sample below, anything with an asterisk as a line comment was added by me.

package com.example.my.mynewapp

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.fragmentX.view.* // *

class MainActivity : AppCompatActivity() {

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

        val textView: TextView = findViewById(R.id.testView) as TextView  // *
        textView.setOnClickListener { // *
            textView.text = "You clicked me! You flipping clicked me!" // *
        } // *

    }
}

Would anyone have any idea what's going on?

like image 976
The Fox Avatar asked Nov 25 '18 18:11

The Fox


People also ask

Why is Kotlin synthetic deprecated?

In November 2020, we announced that this plugin has been deprecated in favor of better solutions, and we recommended removing the plugin from your projects. We know many developers still depend on this plugin's features, and we've extended the support timeframe so you have more time to complete your migrations.


3 Answers

It should have been automatically imported, but there should be

import android.widget.<WhateverIsMissing>

Replace WhateverIsMissing with the reference that is unresolved

like image 108
frogstair Avatar answered Sep 29 '22 03:09

frogstair


if you use Android Studio v.4.2.1 you have to add this line in (build.gradle) file like this:-

id 'kotlin-android-extensions'
like image 43
Mosaad Aljobair Avatar answered Sep 29 '22 03:09

Mosaad Aljobair


You are inflating activity_main.xml in your class.
Does this TextView belong to the above layout?
If it does then you don't need findViewById()
Just add to your imports:

import kotlinx.android.synthetic.main.activity_main.*

and not:

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

then use testView (this is the id of the TextView unless it's a typo) anywhere in your activity class.

like image 20
forpas Avatar answered Sep 29 '22 01:09

forpas