I am new at using Kotlin in Android Studio and I tried to learn on how to use the progress bar by following a simple tutorial on youtube. However, for some reason the "progressBar" on progressBar.max in MainActivity.kt is defined as unresolved reference although my code is identical with the guy in the video.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="335dp"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:scaleY="10" />
</RelativeLayout>
package com.example.game1
import android.animation.ObjectAnimator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
progressBar.max=10
val currentProgress = 6
ObjectAnimator.ofInt(progressBar, propertyName: "progress", currentProgress)
.setDuration(2000)
.start()
}
}
2
Answers
You should get the instance of
ProgressBar
from xml i.ecomplete code
You can use view binding as well to get rid of findViewById
Seems like you’ve watched a tutorial where somebody used Kotlin synthetics to access Views from the code. They are deprecated now and I suggest you use either Muhammad Ahmed solution or View Binding
In module’s build.gradle locate this piece of code:
Now add the view binding build feature, it should look like this:
After you make the changes, a blue bar at the top should appear. Sync your project and now it supports view binding.
Your MainActivity.kt should look like this:
How do you access Views with the view binding? Use camelcase. For example, if you have TextView with id "tv_list_description" it can be accessed in the code like this:
binding.tvListDescription.text = "Sample text"