首页 > 解决方案 > (Android Kotlin)如何在recyclerView中单击按钮从firebase存储中检索图像“名称”?

问题描述

目标:
通过单击按钮从存在于 firebase 存储中的图像中检索默认图像“名称”,以便将名称存储在本地 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>

标签: androidfirebasekotlinandroid-recyclerview

解决方案


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


推荐阅读