androidkotlinandroid-seekbar

How to change the length of the string from the seekbar Android Kotlin


I'm trying to make a password generator as per the length of the seek bar value.

For example when the seek bar is at 12, the password generator will show 12 random characters.

The app works fine with a fixed length which is 16 in this case. MainActivity.

class MainActivity : AppCompatActivity() {

    private lateinit var _binding : ActivityMainBinding
    private var startPoint = 0
    private var endPoint = 0


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _binding = ActivityMainBinding.inflate(layoutInflater)
        val view = _binding.root
        setContentView(view)

        _binding.apply {

            generate.setOnClickListener {
                val generatePassword = randomID()
                Password.text = generatePassword
            }

            seekbar.setOnSeekBarChangeListener(object: SeekBar.OnSeekBarChangeListener{
                override fun onProgressChanged(
                    seekBar: SeekBar?,
                    progress: Int,
                    fromUser: Boolean
                ) {
                    volume.text = progress.toString()
                }

                override fun onStartTrackingTouch(seekBar: SeekBar?) {
                    startPoint = seekBar?.progress ?: 0
                }

                override fun onStopTrackingTouch(seekBar: SeekBar?) {
                    endPoint = seekBar?.progress ?: 0
                }

            })
        }

    }

    private  fun randomID() : String = List(16)  {
      val strings = (('a'..'z') + ('A'..'Z') + ('0'..'9'))
        strings.random()
        }.joinToString("")
    }


Solution

  • Try something like this

     override fun onStopTrackingTouch(seekBar: SeekBar?) {
                   Password.text= randomID(seekBar?.progress ?: 0)
                }
    
     private  fun randomID(length : Int) : String = List(length)  {
          val strings = (('a'..'z') + ('A'..'Z') + ('0'..'9'))
            strings.random()
            }.joinToString("")
        }