zoids3
zoids3

Reputation: 65

android seekBar in kotlin cant create setOnSeekBarChangeListener

hey so I'm trying to make a simple seekbar but I'm facing some weird problems. I programmed an app in kotlin about a year ago and it was different from what I'm experiencing now. first of all, why can I only initialize with lateinit? and then I can only access variables inside onCreate? anyway i was trying to make a seekbar but for some reason kotlin does not recognize it like it dosent understand what I'm trying to do

the code:

class Generator : AppCompatActivity() {


lateinit var username: EditText
lateinit var app: EditText
lateinit var password: TextView

lateinit var caps: Switch
lateinit var numbers: Switch
lateinit var symbols: Switch

lateinit var seekbarvalue: TextView
lateinit var length: SeekBar

lateinit var generate: Button
lateinit var copy: Button
lateinit var save: Button
override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_generator)

    username = findViewById<EditText>(R.id.username)
    app = findViewById<EditText>(R.id.app)
    password = findViewById<TextView>(R.id.password)

    caps = findViewById<Switch>(R.id.caps)
    numbers = findViewById<Switch>(R.id.numbers)
    symbols = findViewById<Switch>(R.id.symbols)

    seekbarvalue = findViewById<TextView>(R.id.seekbarvalue)
    length = findViewById<SeekBar>(R.id.length)

    generate = findViewById<Button>(R.id.generate)
    copy = findViewById<Button>(R.id.copy)
    save = findViewById<Button>(R.id.save)

    length.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener){
        override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {

        }

    }
}

}

Upvotes: 0

Views: 442

Answers (2)

Pratik Fagadiya
Pratik Fagadiya

Reputation: 1472

 length.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
        override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {

        }

        override fun onStartTrackingTouch(p0: SeekBar?) {
            TODO("Not yet implemented")
        }

        override fun onStopTrackingTouch(p0: SeekBar?) {
            TODO("Not yet implemented")
        }

    })

Upvotes: 1

ampedNinja
ampedNinja

Reputation: 31

You can only modify variables beyond initial declaration inside of one of the class' methods, and in this case, onCreate is the only one you've declared.

You must assign them a value at declaration, or make it nullable(optional)/lateinit if you're not sure what the value will need ot be. Using lateinit and trying to use the variable before it's initalized will cause a crash.

You may want to check out this topic for more info: Kotlin - How to decide between "lateinit" and "nullable variable"?

Upvotes: 0

Related Questions