如何为片段设置观察者

Posted

技术标签:

【中文标题】如何为片段设置观察者【英文标题】:How to set up the observer for the fragment 【发布时间】:2021-09-16 16:27:51 【问题描述】:

我认为我已经正确设置了视图模型,但是我在设置观察者时遇到了问题任何帮助将不胜感激

视图模型

class GP1ViewModel() : ViewModel() 

     val gameCardsLiveData: MutableLiveData<List<GameCard>> = MutableLiveData()




         var gameCards: MutableList<GameCard> = ArrayList()
         private var indexOfSelectedPiece: Int? = null



    val images = mutableListOf(
        R.drawable.memorybatcardfront,
        R.drawable.memorycatcardfront,
        R.drawable.memorycowcardfront,
        R.drawable.memorydragonfront,
        R.drawable.memorygarbagemancardfront,
        R.drawable.memoryghostdogcardfront
    )



    init 
        for (image in images) 
            gameCards.add(GameCard(image, imageID = image))
        

        gameCardsLiveData.value = gameCards
        images.addAll(images)
        images.shuffle()
        Log.d(TAG, "ViewModel Created:")

    






     fun updatingModels(position: Int) 
        val gameCard = gameCards[position]

        if (gameCard.isFacedUp) return


        if (indexOfSelectedPiece == null) 
            restoreGameCards()
            indexOfSelectedPiece = position

        
        else 
            checkingForMatch(indexOfSelectedPiece!!, position)
            indexOfSelectedPiece = null
        
        gameCard.isFacedUp = !gameCard.isFacedUp
    

    private fun restoreGameCards() 
        for (gameCard in gameCards) 
            if (!gameCard.isMatched) 
              gameCard.isFacedUp = false

            

        
    

    private fun checkingForMatch(position1: Int, position2: Int) 
        if (gameCards[position1].id == gameCards[position2].id) 
            gameCards[position1].isMatched = true
            gameCards[position2].isMatched = true
        
        else 
            Handler(Looper.getMainLooper()).postDelayed(
                gameCards[position1].isFacedUp = false
                gameCards[position2].isFacedUp = false
            , 1000)
            Log.d(TAG, "checkingForMatch: the lag is called")
        
    


    

片段

class GamePlay1Fragment : Fragment() 

//    lateinit var front_anim: AnimatorSet
//    lateinit var back_anim: AnimatorSet

    private lateinit var viewModel: GP1ViewModel
    private lateinit var pieces: List<ImageView>



    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? 
        val binding: Gameplay1FragmentBinding = DataBindingUtil.inflate(
            inflater,
            R.layout.gameplay1_fragment,
            container, false)



        viewModel = ViewModelProvider(this).get(GP1ViewModel::class.java)

        binding.viewModel = viewModel

        binding.lifecycleOwner = viewLifecycleOwner


        binding.backButtonView.setOnClickListener  v: View ->
            v.findNavController().navigate(GamePlay1FragmentDirections.actionGamePlay1FragmentToLobbyFragment())
        


        viewModel.gameCardsLiveData.observe(viewLifecycleOwner, Observer 
        pieces = listOf(binding.card1back, binding.card2back, binding.card3back, binding.card4back,
            binding.card5back,binding.card6back, binding.card7back,
            binding.card8back, binding.card9back, binding.card10back, binding.card11back,
            binding.card12back)

        if (viewModel.gameCards.isEmpty()) 
            viewModel.gameCards = pieces.indices.map  index ->
                GameCard(viewModel.images[index], false, false, viewModel.images[index]).also 
                    GameCard(id, false, false, viewModel.images[index]).isFacedUp = true
                
            .toMutableList()
        




        pieces.forEachIndexed  index, piece ->
            piece.setOnClickListener 

                viewModel.updatingModels(index)



            
        

    )



        return binding.root
    

只是不确定如何设置观察者。观察者应该能够控制方向的变化,并能够在一秒钟后将卡片翻转过来。谢谢大家。

【问题讨论】:

【参考方案1】:
binding.viewModel.getGameCardsData().observe(viewLifecycleOwner, cards -> 
      // cards will be List<GameCard> and ready to use.
)

// In your viewModel, it is better to access with a getter
private val gameCardsLiveData: MutableLiveData<List<GameCard>> = MutableLiveData()

public fun getGameCardsData() = gameCardsLiveData

【讨论】:

以上是关于如何为片段设置观察者的主要内容,如果未能解决你的问题,请参考以下文章

如何为高度变化添加观察者?

如何为训练观察实现具有自定义权重的 KNN 分类器

如何为模态对话框中呈现的对象运行观察函数?

如何为不同的观察组使用 LAG 和 LEAD 窗口函数

如何为 data.table 中不包括 NA 的更多变量添加滞后并导致每个观察结果?

未调用 LiveData 观察者