문제 설명
BaseActvity/BaseFragment의 ProgressBar 관리 (ProgressBar management in BaseActvity/BaseFragment)
Android 앱에서도 아래와 같은 유사한 문제가 발생한다면 답변을 읽어보세요.
- 모든 액티비티/프래그먼트가 아닌 한 곳에서 진행률 표시줄을 관리해야 합니다.
- BaseActivity/BaseFragment에서 ProgressDialog를 제거하고 싶습니다.
참조 솔루션
방법 1:
There are many options to handling ProgreessBar in Android app. I would like to share my way. Hope it helps some one and save some time.
First of all We are adding a root progress bar in BaseActivity and Same progress bar using in BaseFragment
For Adding a progress bar in BaseActivity override the setContentView(layoutResID) method
BaseActivity.kt
lateinit var progressListener: ProgressListener
private lateinit var progressBar: ProgressBar
override fun setContentView(layoutResID: Int) {
val coordinatorLayout: CoordinatorLayout = layoutInflater.inflate(R.layout.activity_base, null) as CoordinatorLayout
val activityContainer: FrameLayout = coordinatorLayout.findViewById(R.id.layout_container)
progressBar = coordinatorLayout.findViewById(R.id.progressBar) as ProgressBar
binder = DataBindingUtil.inflate(layoutInflater, layoutResId(), activityContainer, true)//to inflate a layout using Data binding
binder.lifecycleOwner = this
super.setContentView(coordinatorLayout)
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
progressListener = ProgressListener(getProgressBar())
}
/**
* open it for overload it in other child activity
* So in case
* If you want to use BaseProgress just ignore it, Don't need to override this fun
* If you want to your progressbar change, Just define in your xml and override the progress bar instance to base
* If you don't want to use Base as well any custom progress just override this and return null
* */
open fun getProgressBar(): ProgressBar? {
return progressBar
}
ProgressListener.kt
class ProgressListener(private val progressBar: ProgressBar?) {
fun showLoading(isVisible: Boolean) {
progressBar?.visibility = if (isVisible) View.VISIBLE else View.GONE
}
}
activity_base.xml
<?xml version="1.0" encoding="utf‑8"?>
<layout>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/layout_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</layout>
And Now For the BaseFragment just access the BaseActivity's progress bar using BaseActivity's instance, and rewrite the open fun for BaseFragment as well.
Note: If you are facing some issue or If I am not able to clarifying the solution properly, Just comment below.
Happy Coding :)