I want to show a progressBar when upload files to server. I can get progress values according to written bytes of file. But I can not update the progress bar. The problem; progress bar is filled to max immediately.
xml:
<ProgressBar
android:id="@ id/progress_file_uploading"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="1" />
In adapter I used a higher order function to get viewHolder. So in this way I can access the progress bar outside of Adapter and use it.
var holderCallback: ((RecyclerView.ViewHolder?) -> Unit) = { }
override fun onBindViewHolder(holder: FileViewHolder, position: Int) {
holder.bind(getItem(position))
holderCallback(holder)
}
In fragment, I have progress values and these values are correct when I debugged.
val countingRequestBody = CountingRequestBody(it) { bytesWritten, contentLength ->
val progress = 1.0 * bytesWritten / contentLength
println("Written: $progress")//0.17,0.35,...1.0 (correct values)
fileAdapter.holderCallback = { holder ->
(holder as FileListAdapter.FileViewHolder).progressBar.progress = progress.toInt()
}
}
So I think there might be a problem with the code in fragment to update progressBar in adapter. I'm not sure this is right way.
The design I want to achieve:
CodePudding user response:
Your progress value is a number between 0 and 1. when you convert it to Int it returns 0 or 1. As you set the maximum value of the progress bar to 1 so progress bar is filled to max immediately. I think you should change the current value like this:
val progress = 100 * (bytesWritten / contentLength)
and also set the max value of the progress bar to 100.
android:max="100"
CodePudding user response:
Define android:max in xml as an integer, not value between 0 and 1. For example, if you set android:max to 100 and progressBar.progress to 25, then 1/4 of progress bar will be filled.