Home > Mobile >  How could the text written in editText modify the progressbar in Kotlin in Android Studio?
How could the text written in editText modify the progressbar in Kotlin in Android Studio?

Time:07-16

I'm trying to make the progress bar interactive with the editText. When the number written in editText is greater than 10, the progress bar increases by 10%.

The code I wrote doesn't work of course but I don't see how to do it:

class MainActivity : AppCompatActivity() {

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

        val progressbar = findViewById<ProgressBar>(R.id.progressBar)
        val converter = findViewById<EditText>(R.id.gamblesum)
        val button = findViewById<Button>(R.id.button6)


        button.setOnClickListener() {
            if (converter > '2') {
                with(progressbar) { incrementProgressBy(10) }

            }

        }

CodePudding user response:

I went with this approach: In the view model create a private and public val. Public val is to be read from/ observed and private val to set the value. Public val gets its value from the private val.

In view model

    private val _progress: MutableLiveData<Int> by lazy { MutableLiveData<Int>() }
val progress: LiveData<Int>
    get() = _progress

in the fragment / activity observe changes to progress. You can make the bar visible or not from here and set the value of the progress at the same time.

viewModel.progress.observe(this.viewLifecycleOwner, Observer<Int> { progress ->
            var value = progress
            if (value>=1){binding.progressBar.isVisible
                binding.progressBar.progress = value
            }else{binding.progressBar.isVisible=false}
        })

Back in your view model you will need some way to reset the progress/make it invisible. For example:

  fun resetProgress() {
    _progress.value = 0
}

When you run some function or do something in the view model you can make the progress bar appear / disappear by changing the value of the private variable

fun getCurrentUserProfileData() = viewModelScope.launch {
    _progress.value = 1
    Log.i(TAG,"user profile : ${userProfile.value}")
    _progress.value = 50
    _userList.value= FirebaseProfileService.generateUserList()
    Log.i(TAG,"user profile List : ${userList.value}")
    _progress.value = 100
    resetProgress()
}

CodePudding user response:

if (converter.text.toString().toIntOrNull() is Int && converter.text.toString().toInt() > 10 {
    progressBar.progress = (progrrssBar.progress * 1.1).toInt()
}

You need to compare the value converted to an integer against an integer and not a string. You can save the first conditional if the EditText only accepts numbers, otherwise you have to validate that I entered it

  • Related