android - (Android Kotlin)如何在recyclerView中单击按钮从firebase存储中检索图像“名称”?
问题描述
目标:
通过单击按钮从存在于 firebase 存储中的图像中检索默认图像“名称”,以便将名称存储在本地 txt 文件中。(稍后将用于过滤掉图像)。
到目前为止的设置:
- 已创建 recyclerView,它在 cardView 中显示来自 firebase 存储的图像。
- recyclerView 中的每张卡片仅包含图像和一个按钮“doneButton”。
- 已设置将字符串保存在本地 txt 文件中的功能。
我被困在哪里:
无法在单击按钮时从存储中检索图像名称,这两者(按钮和图像)都存在于 recyclerView 的卡片上。
检索到名称后,在同一个按钮单击操作上,需要将图像名称传递给保存图像名称函数以将其写入本地 txt 文件。
如果有人可以帮助解决这个问题,那将非常有帮助。谢谢你。(仅供参考:我是 android 开发新手)
主要活动:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_numbers_tab)
//firebase
val storage = FirebaseStorage.getInstance()
val storageRef = storage.reference.child("Images")
val imageList:ArrayList<CoronaImages> = ArrayList()
val listAllTask: Task<ListResult> = storageRef.listAll()
listAllTask.addOnCompleteListener{ result ->
val items: List<StorageReference> = result.result!!.items
//cycle for adding image URL to list
items.forEachIndexed { index, item ->
item.downloadUrl.addOnSuccessListener {
Log.d("item","$it")
imageList.add(CoronaImages(it.toString()))
}.addOnCompleteListener{
ImageRecyclerView.adapter = ImageAdapter(imageList, this)
ImageRecyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true)
}
}
}
}
适配器(尝试为图像名称创建 OnClickListener):
class ImageAdapter (
private var coronaImage: List<CoronaImages>, private val context: Context):
RecyclerView.Adapter<ImageAdapter.ViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutInflater.from(context).inflate(R.layout.corona_images, parent, false)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = coronaImage[position]
Picasso.get()
.load(item.imageUrl)
.into(holder.imageView)
}
override fun getItemCount(): Int {
return coronaImage.size
}
class ViewHolder(view: View):RecyclerView.ViewHolder(view), View.OnClickListener {
val imageView: ImageView=view.findViewById(R.id.imageView1)
// this is where I'm stuck:
val doneButton: CardView=view.findViewById(R.id.doneButton)
init {
doneButton.setOnClickListener {
object : View.OnClickListener {
override fun onClick(v: View?) {
// how can I retrieve the image name and pass it to the writeToFile ()??
writeToFile(????)
}
}
}
}
// Function to Write to a File
fun writeToFile(FirebaseImageName: String) {
try {
var writeData = FileWriter("doneCoronaImages.txt", true)
writeData.write(FirebaseImageName +"\n")
writeData.close()
}
catch (ex: Exception) {
print("Could not save the image name.")
}
}
}
}
图片 URL 的数据类:
data class CoronaImages(
var imageUrl: String
)
电晕图像 XML
<com.google.android.material.card.MaterialCardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/card"
android:layout_width="match_parent"
android:layout_height="455dp"
android:layout_margin="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Media -->
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="390dp"
android:scaleType="centerCrop" />
<!-- Buttons -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:orientation="horizontal">
<Button
android:id="@+id/coronaButton" style="@style/Widget.MaterialComponents.Button.TextButton.Icon"
android:layout_width="90sp"
android:layout_height="55sp"
android:layout_marginStart="0dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="0dp"
android:text="@string/coronaButtonTitle"
android:textSize="16sp"/>
</LinearLayout>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
解决方案
doneButton.setOnClickListener {
val item = coronaImage[adapterPosition] // get image item
val imageName = File(item.imageUrl).name // get image name
writeImageNameToFile(context, "doneCoronaImages.txt", imageName)
}
或者
view.setOnClickListener {
val item = coronaImage[adapterPosition] // get image item
val imageName = File(item.imageUrl).name // get image name
writeImageNameToFile(context, "doneCoronaImages.txt", imageName)
}
创建文件夹并写入文件。
fun writeImageNameToFile(
context: Context,
fileName: String?,
imageName: String?
) {
try {
val root = File(context.getExternalFilesDir(null), "YourFolder")
if (!root.exists()) {
root.mkdirs() // create folder if you want
}
// val root = File(context.getExternalFilesDir(null)?.absolutePath) // use this line if you don't want to create folder
val txtFile = File(root, fileName)
val writer = FileWriter(txtFile, true)
writer.appendln(imageName)
writer.flush()
writer.close()
Toast.makeText(context, "Saved image", Toast.LENGTH_SHORT).show()
} catch (e: IOException) {
e.printStackTrace()
}
}
设备文件资源管理器 -> 存储 -> 模拟 -> 0 -> Android -> 数据 -> YourPackageName -> 文件 -> YourFolder -> doneCoronaImages.txt
推荐阅读
- python - 调用 setter 属性作为您的 _init_ 方法定义是不好的做法吗?
- javascript - React axios 发送多张图片formdata
- python - pep8 是否允许在打印中使用 \t
- visual-studio - 发布网络应用程序但不覆盖 app_data 但删除现有文件?
- flutter - 包:flutter/src/widgets/basic.dart':断言失败:第 2297 行 pos 15:'heightFactor == null || heightFactor >= 0.0':不正确
- java - Jacoco Maven 覆盖率报告始终为 0%
- java - 如何从按钮获取文本以编辑文本?
- python - 在通过套接字建立连接时,python 会向 Web 服务器发送有关主机的哪些详细信息?
- android - Android房间从表中选择不同的table.calender
- c++ - 在 C++ 中序列化/反序列化位域结构