【问题标题】:Passing values from one fragment to another将值从一个片段传递到另一个片段
【发布时间】:2020-05-31 08:24:55
【问题描述】:

我在 Kotlin 工作并使用改造。我有一个回收者视图,它由卡片组成。每张卡片都有一个 typeName 和一个与之关联的图像,现在我已经使用数据类静态添加。现在,一旦用户单击特定卡片,我只需将 typeName 从 CategoryFragment 传递给 LocationFragment。在 LocationFragment 中,我想检查数据库中的纬度、经度和 typeName 是否已经存在。

这是我的 Category 数据类代码: 数据类 Category_dataclass ( val category_image : Int , val typeName: String)

这是我的 CategoryFragment 代码:

package com.example.atry.MakeComplaint

import android.content.Context
import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.atry.History.Complaints
import com.example.atry.History.MyComplainRecyclerViewAdapter

import com.example.atry.R
import kotlinx.android.synthetic.main.existing_complaint_popup.*


class CategoryFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {

        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val v = inflater.inflate(R.layout.fragment_category, container, false)
        val recyclerView = v.findViewById(R.id.category_list) as RecyclerView

        recyclerView.apply {
            layoutManager = GridLayoutManager(context!!, 2)
        }

        //creating an arraylist to store category using the data class user
        val category = ArrayList<Category_dataclass>()

        //adding some dummy data to the list of categories
        category.add(Category_dataclass((R.drawable.trash) , "Water"))
        category.add(Category_dataclass((R.drawable.fire) , "Sewerage"))
        category.add(Category_dataclass((R.drawable.dustbin) , "load"))




        //creating our adapter
        val adapter = CategoryRecyclerViewAdapter(category)

        //now adding the adapter to recyclerview
        recyclerView.adapter = adapter


        // Inflate the layout for this fragment
        return v



    }




    }

这是 CategoryRecyclerViewAdapter:

package com.example.atry.MakeComplaint

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.example.atry.History.ComplaintDetailsFragment
import com.example.atry.History.Complaints
import com.example.atry.MakeComplaint.Category_dataclass
import com.example.atry.MakeComplaint.CategoryRecyclerViewAdapter
import com.example.atry.R
import java.util.*
import kotlin.collections.ArrayList

class CategoryRecyclerViewAdapter(val categoryList: ArrayList<Category_dataclass>) : RecyclerView.Adapter<CategoryRecyclerViewAdapter.ViewHolder>() {




    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryRecyclerViewAdapter.ViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.fragment_category_single, parent, false)
        return ViewHolder(v)
    }

    //this method is binding the data on the list
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bindItems(categoryList[position])
        holder.mView.setOnClickListener{view->



            val lFragment = LocationFragment()
            val oldFragment = CategoryFragment()
            val manager = (holder.mView.context as AppCompatActivity).supportFragmentManager
            val transaction =  manager.beginTransaction()
            transaction.replace(
                R.id.first_screen_of_makecomplaint,
                lFragment
            ) // give your fragment container id in first parameter
            transaction.show(lFragment)
            transaction.hide(oldFragment)
            transaction.isAddToBackStackAllowed
            transaction.addToBackStack(oldFragment.fragmentManager.toString())  // if written, this transaction will be added to backstack
            transaction.commit()

        }
    }


    //this method is giving the size of the list
    override fun getItemCount(): Int {
        return categoryList.size
    }


    inner class ViewHolder(val mView : View) : RecyclerView.ViewHolder(mView) {
        fun bindItems(cat:Category_dataclass) {
            val imageViewName = mView.findViewById(R.id.category_image) as ImageView
            val textViewtext = mView.findViewById(R.id.category_text) as TextView

            imageViewName.setImageResource(cat.category_image)
            textViewtext.text = cat.typeName


        }



    }

}

这是我的改造:

 //to check existing complaint

    @GET("api/existingComplain")
    @FormUrlEncoded
    fun checkExistingComplain(@Query("typeName") typeName:String,
                              @Query("longitude") longitude:String,
                              @Query("latitude") latitude:String):Observable<Observables.checkExistingResult>

我已经创建了我存储数据类的对象,它将返回以下内容:

data class checkExistingResult(val description:String , val Complain:String)

如果数据库中已经存在 typeName 和 location,我希望将描述和投诉显示在材质样式的对话框中。

【问题讨论】:

    标签: android-fragments kotlin retrofit


    【解决方案1】:

    你可以试试这个:

    第一步:-

    val dashboard = "Dashboard"
    

    像这样取变量,你可以把它的名字作为你的片段名称,所以你可以像这样检查页面名称MainActivity().dashboard

    现在,第二步:-

    创建一个类并在该类中编写这样的函数

     fun openPage(
        activity: Activity,
        pagename: String?, model: PaymentDetails
    ) {
        when (pagename) {
    
                MainActivity().dashboard -> {
                    val mfragment = DashboardFragment()
                    (activity as MainActivity).fragmentManager.beginTransaction()
                        .replace(R.id.nav_host, mfragment).commit()
    
                    val a = Bundle()
                    a.putSerializable("model", model)
                    mfragment.arguments = a
                }
            }
        }
    

    在我的整个模型中获取键值对,并且键是 model 在我的代码中你可以写任何东西。

    第三步:-

    使您的模型可序列化

    第四步:-当您将值添加到模型中时,添加详细信息并为您想要使用这些值的方法添加模型,如下所示

    val payment = PaymentDetails(
                type,
                price,
                name,
                id,
             )
            paymentData!!.add(payment)
            CustomMethods().openPagePaymentDetails(
                activity!!,
                MainActivity().sessionPaymentFragment, payment
            )
    

    第五步:-

    使用您的模型类型声明并初始化您的对象,如下所示:

     //Declare 
     private var model: PaymentDetails? = null 
    
    //initialise
     model = arguments!!.getSerializable("model") as PaymentDetails?
    

    现在终于可以像这样将前一个片段的值访问到下一个片段中,

    var type: String
    type = model!!.type
    

    注意:- 请不要忘记让您的模型类可序列化

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2016-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-14
      • 1970-01-01
      相关资源
      最近更新 更多