Jake Choi
Jake Choi

Reputation: 151

findViewByID does not work when used virtually or normally

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.

Upvotes: 0

Views: 144

Answers (1)

S T
S T

Reputation: 1134

findViewByID change to findViewById

if not, add as for type like this

lateinit var mTextHello: TextView

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

    mTextHello = findViewById(R.id.ui_text_hello) as TextView
    mTextHello.text = "Kotlin Example"

}

Upvotes: 1

Related Questions