BaseActvity/BaseFragment 中的 ProgressBar 管理

ProgressBar management in BaseActvity/BaseFragment

阅读答案,如果您在 Android 应用中也遇到类似问题,如下所示

在 Android 应用程序中有许多处理 ProgressBar 的选项。我想分享我的方法。希望它能帮助一些人并节省一些时间。

首先,我们在 BaseActivity 中添加一个根进度条,并在 BaseFragment 中使用相同的进度条

要在 BaseActivity 中添加进度条,请覆盖 setContentView(layoutResID) 方法

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>

现在对于 BaseFragment,只需使用 BaseActivity 的实例访问 BaseActivity 的进度条,并重写 BaseFragment 的打开乐趣。

注意:如果您遇到问题或者我无法正确阐明解决方案,请在下方评论。

快乐编码:)