您好,登录后才能下订单哦!
在Android应用开发中,网络请求、文件读写等耗时操作通常需要在后台线程中执行,以避免阻塞主线程导致界面卡顿。为了提升用户体验,通常会在这些耗时操作执行时显示一个等待框(如ProgressDialog或自定义的加载动画),以提示用户当前操作正在进行中。本文将介绍如何封装一个通用的等待框工具类,并结合网络请求等延时操作进行示例分析。
等待框的主要作用是: - 提示用户当前正在进行耗时操作,避免用户误以为应用无响应。 - 增强用户体验,提供视觉反馈。
为了实现一个通用的等待框工具类,我们需要考虑以下几点: 1. 封装性:将等待框的创建、显示和隐藏逻辑封装到一个工具类中,便于复用。 2. 灵活性:支持自定义等待框的样式和提示信息。 3. 线程安全:确保等待框的显示和隐藏操作在主线程中执行。 4. 兼容性:适配不同的Android版本和设备。
以下是一个简单的等待框工具类的实现:
import android.app.ProgressDialog
import android.content.Context
import android.os.Handler
import android.os.Looper
class LoadingDialogUtil private constructor() {
private var progressDialog: ProgressDialog? = null
companion object {
private val instance = LoadingDialogUtil()
fun getInstance(): LoadingDialogUtil {
return instance
}
}
// 显示等待框
fun showLoading(context: Context, message: String = "加载中...") {
dismissLoading() // 先关闭之前的等待框
Handler(Looper.getMainLooper()).post {
progressDialog = ProgressDialog(context).apply {
setMessage(message)
setCancelable(false) // 不可取消
show()
}
}
}
// 隐藏等待框
fun dismissLoading() {
Handler(Looper.getMainLooper()).post {
progressDialog?.dismiss()
progressDialog = null
}
}
}
Handler(Looper.getMainLooper())
确保show
和dismiss
方法在主线程中执行。showLoading
方法支持自定义提示信息。以下是一个结合网络请求的示例,展示如何使用封装的等待框工具类。
在build.gradle
中添加Retrofit和OkHttp依赖:
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:okhttp:4.9.3'
}
import retrofit2.Call
import retrofit2.http.GET
interface ApiService {
@GET("posts/1")
fun getPost(): Call<Post>
}
data class Post(
val userId: Int,
val id: Int,
val title: String,
val body: String
)
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class MainActivity : AppCompatActivity() {
private val loadingDialogUtil = LoadingDialogUtil.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 显示等待框
loadingDialogUtil.showLoading(this, "正在加载数据...")
// 发起网络请求
val retrofit = Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val apiService = retrofit.create(ApiService::class.java)
apiService.getPost().enqueue(object : Callback<Post> {
override fun onResponse(call: Call<Post>, response: Response<Post>) {
// 隐藏等待框
loadingDialogUtil.dismissLoading()
if (response.isSuccessful) {
val post = response.body()
// 处理数据
println("Title: ${post?.title}")
} else {
// 处理错误
println("请求失败: ${response.code()}")
}
}
override fun onFailure(call: Call<Post>, t: Throwable) {
// 隐藏等待框
loadingDialogUtil.dismissLoading()
// 处理异常
println("请求异常: ${t.message}")
}
})
}
}
showLoading
方法显示等待框。dismissLoading
方法隐藏等待框。enqueue
方法发起异步网络请求,避免阻塞主线程。如果需要更复杂的等待框样式,可以使用自定义View或第三方库(如Lottie动画)替换ProgressDialog
。
为网络请求设置超时时间,并在超时后隐藏等待框:
val okHttpClient = OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.build()
val retrofit = Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
在多个请求同时进行时,可以使用计数器控制等待框的显示和隐藏:
private var requestCount = 0
fun showLoading() {
requestCount++
if (requestCount == 1) {
loadingDialogUtil.showLoading(this)
}
}
fun dismissLoading() {
requestCount--
if (requestCount == 0) {
loadingDialogUtil.dismissLoading()
}
}
通过封装等待框工具类,我们可以简化代码并提升开发效率。结合网络请求等延时操作,等待框能够有效提升用户体验。在实际开发中,可以根据需求进一步优化等待框的样式和功能,例如支持自定义动画、超时处理等。希望本文的示例和分析能为您的Android开发提供参考和帮助!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。