kotlin:如何在两个片段之间传递数据

时间:2018-04-15 00:32:01

标签: android android-fragments kotlin fragment android-listfragment

我有一个简单的应用程序,有一个Activity,RecyclerView适配器,RecyclerView片段和其他片段,以显示我在RecyclerView中单击该项目的数据,但我的问题是我不知道如何通过单击传递数组行的数据显示新片段后显示的乐趣 MainActivity.kt

class MainActivity : AppCompatActivity(),ContentAdapter.ContentListener{
override fun onItemClicked(item: MainMarketTickClass) {
        var ft1 : FragmentTransaction = supportFragmentManager.beginTransaction()
        ft1.replace(R.id.MainFrame,AddCar.newInstanceaddcar())
        ft1.commit()}
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContentView(R.layout.activity_main)
    var bnv = findViewById(R.id.navigation) as BottomNavigationView
    bnv.setOnNavigationItemSelectedListener (object : BottomNavigationView.OnNavigationItemSelectedListener{
        override fun onNavigationItemSelected(item: MenuItem): Boolean {
            var selectFragment : Fragment? = null
            when (item.itemId) {
                R.id.navigation_home -> {
                    selectFragment = MainMarket.newInstance()
                }
                R.id.navigation_dashboard -> {
                   selectFragment = AddCar.newInstanceaddcar()
                }
                R.id.navigation_notifications -> {

                }
            }
            var ft : FragmentTransaction = supportFragmentManager.beginTransaction()
            ft.replace(R.id.MainFrame,selectFragment)
            ft.commit()
            return true
        }
    })

    var ft : FragmentTransaction = supportFragmentManager.beginTransaction()
    ft.replace(R.id.MainFrame,MainMarket.newInstance())
    ft.commit()
}

}

ContentAdapter.kt

class ContentAdapter constructor(private val activity: MainActivity, private var listOfData: ArrayList<MainMarketTickClass>, val listener: ContentListener) : RecyclerView.Adapter<ContentAdapter.ViewHolder>() {

override fun getItemCount(): Int = listOfData.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    var inf = ViewHolder(LayoutInflater.from(parent!!.context).inflate(R.layout.maintick, parent, false))
    return inf

}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.bind(listOfData, listener)
}

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

    fun bind(listOfData: ArrayList<MainMarketTickClass>, listener: ContentListener) {
        val dataListin2 = listOfData[adapterPosition]

        itemView.textView.text = dataListin2.title

       interface method implemented in the Activity
        itemView.setOnClickListener {
            listener.onItemClicked(listOfData.get(adapterPosition))
        }
    }
}

public interface ContentListener {
    fun onItemClicked(item: MainMarketTickClass)
}

MainMarket.kt

class MainMarket: Fragment(),ContentAdapter.ContentListener{

var ITEMSList = ArrayList<MainMarketTickClass>()
companion object {
   fun newInstance():Fragment{

       var fb : MainMarket = MainMarket()
       return fb
   }
}


override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    var inf = inflater!!.inflate(R.layout.main_marker,container,false)
    return inf


}

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

    ITEMSList .add ( MainMarketTickClass("123"))
    ITEMSList .add ( MainMarketTickClass(" 123"))
    ITEMSList .add ( MainMarketTickClass("123"))


    var adapter = ContentAdapter (MainActivity(),ITEMSList,this)
    list.adapter = adapter
    list.layoutManager = LinearLayoutManager(this.context,LinearLayoutManager.VERTICAL,false)

}

override fun onItemClicked(item: MainMarketTickClass) {
    if(activity is MainActivity){
        (activity as MainActivity).onItemClicked(item)

    }

}

addcar.kt

class AddCar: Fragment(), ContentAdapter.ContentListener{


companion object {
   fun newInstanceaddcar(): Fragment {

       var fb : AddCar = AddCar()
       val args = Bundle()

       fb.arguments = args

       return fb
   }
}





override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater!!.inflate(R.layout.add_car,container,false)



}

 override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
     val TextView= view!!.findViewById(R.id.textView) as TextView
     var titlein = ""

}
override fun onItemClicked(item: MainMarketTickClass) {


}

3 个答案:

答案 0 :(得分:1)

您应该将特定位置的单个数据传递给listOfData,而不是将ContentAdapterViewHolder传递到ViewHolder。在这里,我从您的ContentAdapter

进行了更改
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.bind(listOfData[position], listener)
}

而你的ViewHolder应该是这样的:

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

    fun bind(data: MainMarketTickClass, listener: ContentListener) {
        itemView.setOnClickListener {
            listener.onItemClicked(data)
        }
    }
}

要在片段之间传输数据,您可能需要阅读Communicating with Other Fragments。您的ContentListener应该在MainMarket

class MainMarket: Fragment() {
private lateinit var mCallback: ContentListener

// Container Activity must implement this interface
interface ContentListener {
    fun onItemClicked(item: String)
}

override fun onAttach(context: Context?) {
    super.onAttach(context)
    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception
    try {
        mCallback = context as ContentListener
    } catch (e: ClassCastException) {
        throw ClassCastException(activity.toString()
                + " must implement OnHeadlineSelectedListener")
    }
}

并在ContentListener

中实施Activity
class MainActivity : AppCompatActivity(), MainMarket.ContentListener {

override fun onItemClicked(item: MainMarketTickClass) {
    val bundle = Bundle()
    bundle.putParcelable("data", item)

    val addCar = AddCar()
    addCar.arguments = bundle

    var ft : FragmentTransaction = supportFragmentManager.beginTransaction()
    ft.replace(R.id.frameLayout,addCar)
    ft.commit()
}

如果要将对象带到另一个片段,则应考虑使用Parcelable实现对象。以下是Send object using parcelable的一些示例。
希望它会对你有所帮助。

答案 1 :(得分:0)

在片段之间传递数据的方法是:

  • 捆绑(首选)
  • SharedPreferences
  • 数据库

因此,在你需要的newInstanceaddcar(): Fragment传递中作为参数数据,set使用bundle.putType()(其中type是Int,Boolean,Serializable等),并在你的片段代码中使用{{获取这些数据1}}。 这样,您可以将任何可序列化类型传递给其他片段。

答案 2 :(得分:-1)

这是一个对我有用的好教程。在本教程中,我们在第一个片段中创建一个包,然后将其放入该包中。最后,我们使用其参数将数据发送到第二个捆绑软件。

Kotlin Tutorial: Transfer data between Fragments -Android Studio Tutorials