Android Studio Kotlin-如何从对话框片段添加项目到回收视图

wsewodh2  于 2022-11-16  发布在  Android
关注(0)|答案(1)|浏览(130)

我想通过单击按钮(该按钮在购物篮对话框片段中称为addToBasket)将项目从购物篮对话框片段添加到位于购物篮片段中的回收视图
有一个GlassContainerActivity,通过单击该项目可以从中打开BasketDialogFragment,我需要将该项目(已打开)添加到购物篮(BasketFragment)中
玻璃容器活动

package com.example.slvglass.activity

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.widget.*
import androidx.fragment.app.FragmentTransaction
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.slvglass.R
import com.example.slvglass.adapters.GlassConAdapter
import com.example.slvglass.adapters.MirrorAdapter
import com.example.slvglass.fragments.BasketDialogFragment
import com.example.slvglass.fragments.BasketFragment
import com.example.slvglass.models.AddToBasket

import com.example.slvglass.models.Subcategory
import com.google.android.material.appbar.MaterialToolbar
import com.google.firebase.database.*

class GlassContainerActivity : AppCompatActivity() {

    private lateinit var toolbar: MaterialToolbar

    private var dbref : DatabaseReference? = null

    private lateinit var glassConRecyclerView: RecyclerView
    private lateinit var basketList : ArrayList<AddToBasket>

    private var list = mutableListOf<Subcategory>()
    private var adapter : GlassConAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_glass_container)

        adapter = GlassConAdapter(applicationContext)

        glassConRecyclerView = findViewById(R.id.glassCon_gridView)
        glassConRecyclerView.layoutManager = GridLayoutManager(applicationContext, 2)
        glassConRecyclerView.adapter = adapter

        dbref = FirebaseDatabase.getInstance().getReference("Subcategory").child("Glass Container")

        toolbar = findViewById(R.id.glassCon_Toolbar)
        toolbar.title = "Стеклотара"
        toolbar.setNavigationIcon(R.drawable.ic_back_arrow)
        setSupportActionBar(toolbar)

        val actionBar = supportActionBar

        actionBar!!.setDisplayHomeAsUpEnabled(true)

        /*passData()*/



        getGlassConData()

    }

    private fun getGlassConData(){

        dbref?.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {

                for (glassConSnapshot in snapshot.children){

                    val title = glassConSnapshot.child("title").value.toString()
                    val img = glassConSnapshot.child("img").value.toString()
                    val capacity = glassConSnapshot.child("capacity").value.toString()
                    val glassCon = Subcategory(title = title, img = img, capacity = capacity)
                    list.add(glassCon)

                    adapter?.setOnItemClickListener(object  : GlassConAdapter.onItemMenuClickListener{
                        override fun onItemCLick(position: Int) {

                            val dialog = BasketDialogFragment()
                            dialog.show(supportFragmentManager, "basketDialog")
                            val bundle = Bundle()
                            bundle.putInt("position", position)
                            dialog.arguments = bundle

                        }

                    })

                }

                adapter?.setItems(list)

            }

            override fun onCancelled(error: DatabaseError) {

                Toast.makeText(this@GlassContainerActivity, error.toString(), Toast.LENGTH_SHORT).show()

            }

        })

    }

    override fun onSupportNavigateUp(): Boolean {
        onBackPressed()
        return true
    }
}

购物篮片段

package com.example.slvglass.fragments

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.slvglass.R
import com.example.slvglass.activity.GlassContainerActivity
import com.example.slvglass.adapters.AddToBasketAdapter
import com.example.slvglass.models.AddToBasket
import com.google.firebase.database.DatabaseReference

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [BasketFragment.newInstance] factory method to
 * create an instance of this fragment.
 */

private lateinit var basketRecycler: RecyclerView
lateinit var basketAdapter: AddToBasketAdapter
private lateinit var basketList: ArrayList<AddToBasket>
private lateinit var title: String
private lateinit var capacity: String
private var dbref : DatabaseReference? = null
private lateinit var frameBasket : FrameLayout
private lateinit var glassContainerActivity: GlassContainerActivity
private lateinit var basketDialogFragment: BasketDialogFragment


class BasketFragment : Fragment() {
    // TODO: Rename and change types of parameters

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        return inflater.inflate(R.layout.fragment_basket, container, false)

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        basketList = ArrayList()
        basketRecycler = view.findViewById(R.id.basketRecycler)
        basketAdapter = AddToBasketAdapter(basketList, view.context)
        basketRecycler.adapter = basketAdapter
        basketRecycler.layoutManager = LinearLayoutManager(view.context)
        basketRecycler.setHasFixedSize(true)

    }
}

添加到购物篮适配器

package com.example.slvglass.adapters

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.slvglass.GlideApp
import com.example.slvglass.R
import com.example.slvglass.fragments.BasketDialogFragment
import com.example.slvglass.models.AddToBasket
import com.example.slvglass.models.Subcategory

class AddToBasketAdapter(private var basketList: List<AddToBasket>, private var context: Context) : RecyclerView.Adapter<AddToBasketAdapter.AddToBasketViewHolder>(){

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AddToBasketViewHolder {

        val view = LayoutInflater.from(parent.context).inflate(R.layout.basket_item, parent, false)
        return AddToBasketViewHolder(view)

    }

    override fun onBindViewHolder(holder: AddToBasketViewHolder, position: Int) {

        val currentItem = basketList[position]

        holder.basketTitle.text = currentItem.title
        holder.basketDescription.text = currentItem.capacity

        GlideApp.with(context).load(currentItem.img).into(holder.basketImg)

    }

    override fun getItemCount(): Int {
        return basketList.size
    }

    fun setItems(list: List<AddToBasket>){

        this.basketList = list
        notifyDataSetChanged()

    }

    class AddToBasketViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){

        val basketTitle : TextView = itemView.findViewById(R.id.basketTitle)
        val basketDescription : TextView = itemView.findViewById(R.id.basketDescription)
        val basketImg : ImageView = itemView.findViewById(R.id.basketImg)

    }

}

AddToBasket(数据类别)

package com.example.slvglass.models

data class AddToBasket(var title: String ?= null, var capacity: String ?= null, var img: String ?= null, var id: Int ?= null)

购物篮对话框片段

package com.example.slvglass.fragments

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import androidx.recyclerview.widget.RecyclerView
import com.example.slvglass.GlideApp
import com.example.slvglass.R
import com.example.slvglass.adapters.AddToBasketAdapter
import com.example.slvglass.databinding.FragmentBasketDialogBinding
import com.example.slvglass.models.AddToBasket
import com.google.firebase.database.*

class BasketDialogFragment : DialogFragment() {

    private lateinit var titleText : TextView
    private lateinit var capacityText : TextView
    private lateinit var imgImg : ImageView
    private lateinit var corolla : TextView
    private lateinit var addToBasket : Button
    private lateinit var basketList : ArrayList<AddToBasket>
    private lateinit var basketAdapter: AddToBasketAdapter
    private lateinit var basketRecycler : RecyclerView
    private var dbref : DatabaseReference? = null
    private lateinit var basketFragment: BasketFragment
    private lateinit var basketDialogFragment: BasketDialogFragment

    private var _binding: FragmentBasketDialogBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentBasketDialogBinding.inflate(inflater, container, false)

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        basketDialogFragment = BasketDialogFragment()

        corolla = view.findViewById(R.id.dialogCorolla)

        addToBasket = view.findViewById(R.id.addToBasket)

        basketList = ArrayList()

        basketRecycler = view.findViewById(R.id.basketRecycler)

        basketAdapter = AddToBasketAdapter(basketList, view.context)


        dbref = FirebaseDatabase.getInstance().getReference("Subcategory").child("Glass Container")

        dbref?.addValueEventListener(object : ValueEventListener{
            @SuppressLint("ResourceType")
            override fun onDataChange(snapshot: DataSnapshot) {

                for (dialogSnapshot in snapshot.children){

                    val title = dialogSnapshot.child("title").value.toString()
                    val capacity = dialogSnapshot.child("capacity").value.toString()
                    val img = dialogSnapshot.child("img").value.toString()
                    val id = dialogSnapshot.child("id").value.toString().toInt()

                    val dialog = AddToBasket(title, capacity, img, id)

                    val position = arguments?.get("position").toString().toInt()

                    titleText = view.findViewById(R.id.dialogTitle)
                    capacityText = view.findViewById(R.id.dialogCapacity)
                    imgImg = view.findViewById(R.id.dialogImg)

                    val posCheck = position + 1
                    basketFragment = BasketFragment()

                    if (id == posCheck){

                        titleText.text = dialog.title
                        capacityText.text = dialog.capacity
                        GlideApp.with(view.context).load(dialog.img).into(imgImg)

                        addToBasket.setOnClickListener {

                            basketList.add(dialog)
                            basketRecycler.adapter = basketAdapter
                            basketAdapter.notifyItemInserted(position)

                            Toast.makeText(context, "Добавлено", Toast.LENGTH_SHORT).show()


                        }

                    }

                }

            }

            override fun onCancelled(error: DatabaseError) {

            }

        })

    }

}
dxpyg8gm

dxpyg8gm1#

嗨,Gangsta,我建议你使用MVVM,并使用保存循环视图和对话框片段更新的活动创建共享的视图模型----
首先你创建你的viewmodel class MainViewModel :ViewModel(){ val addFragmentLiveData= MutableLiveData<Object>()}然后在你的Fragment val viewmodel= ViewModelProvider(activity)[ MainViewModel::class.java] viewmodel.addFragmentLiveData.value = Object() viewmodel.addFragmentLiveData.value = null在你的Activity val viewmodel= val viewmodel= ViewModelProvider(this)[ MainViewModel::class.java] viewModel.remindersList.observe(this){ if(it !=null)// addFragment() }中抱歉延迟,如果注解格式不好,但是Stackoverflow有一些错误

相关问题