在另一个片段中,我想删除所有内容或重置它们并用新值重新填充它。单击按钮可在另一个片段中实现此目的。也许有更好的方法可以执行此操作,所以我将代码放入问题中。
使用片段B中的ViewModel填充片段A中的值:
将我的数据发送到片段B到A:
startButton.setOnClickListener { v ->
Log.d("Hur", activity!!.supportFragmentManager.fragments.size.toString())
val spinnerVal = sizeSpinner.selectedItem.toString().toInt()
val map = HashMap<String, Any>()
wordList.sortByDescending { it.length }
Log.d("Tag", wordList.toString())
map["words"] = wordList
map["rowSize"] = spinnerVal
map["columnSize"] = spinnerVal
loaded++
map["loaded"] = loaded
gameData?.data?.postValue(map)
(activity as MainActivity).getViewPager().setCurrentItem(0)
}
我正在使用ViewPagerListener检索片段A中的值:
片段A-OnCreateView:
val pager = (activity as MainActivity).getViewPager()
pager.addOnPageChangeListener(object : OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
override fun onPageSelected(position: Int) {
if(position == 0) {
Log.d("Tag", "Inside")
activity?.let {
Log.d("Tag", "Hello World!")
val gameData = ViewModelProviders.of(it).get(GameData::class.java)
observeInput(gameData)
}
}
}
})
observeInput:
gameData.data.observe(this, Observer {
it?.let {
words = it["words"] as ArrayList<String>
columnSize = it["columnSize"] as Int
rowSize = it["rowSize"] as Int
Log.d("yes", "Starting Game")
if(rowSize != 0 && columnSize != 0 && !words.isEmpty() && !loaded) {
Log.d("inside", "yes")
wordGrid = Array(rowSize) { Array(columnSize) { "" } }
findLocations()
initLayouts()
}
}
})