写kotlin代码 功能为 加载数据为空时的占位图支持点击刷新的工具类
时间: 2024-03-21 20:42:56 浏览: 11
好的,我会尽力来回答你的问题。以下是一个样例 Kotlin 工具类,用于在数据加载为空时显示占位图,并支持点击刷新:
```kotlin
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
class EmptyStateUtils(private val context: Context) {
fun showEmptyState(
parent: ViewGroup,
message: String,
imageRes: Int,
clickListener: (() -> Unit)? = null
) {
val emptyStateView = LayoutInflater.from(context).inflate(R.layout.layout_empty_state, parent, false)
parent.addView(emptyStateView)
val messageTextView = emptyStateView.findViewById<TextView>(R.id.empty_state_message)
val imageView = emptyStateView.findViewById<ImageView>(R.id.empty_state_image)
messageTextView.text = message
imageView.setImageResource(imageRes)
if (clickListener != null) {
emptyStateView.setOnClickListener { clickListener.invoke() }
}
}
fun hideEmptyState(parent: ViewGroup) {
parent.removeAllViews()
}
}
```
此工具类使用 LayoutInflater 从一个指定的 layout 文件中创建了一个占位图视图。当需要显示占位图时,我们可以调用 showEmptyState() 函数,该函数将占位图添加到指定的 ViewGroup 中,同时设置了占位图的文本和图像资源。如果需要支持点击刷新,则可以传入一个回调函数。
当不再需要占位图时,我们可以调用 hideEmptyState() 函数,该函数将从指定的 ViewGroup 中移除占位图视图。
此工具类的占位图布局可以通过 layout_empty_state.xml 文件来定义:
```xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/empty_state_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="@+id/empty_state_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_empty_state" />
<TextView
android:id="@+id/empty_state_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No data available." />
</LinearLayout>
```
当然,你可以根据自己的需求来修改布局文件。希望这个样例代码能对你有所帮助!