【发布时间】:2022-11-19 00:53:07
【问题描述】:
- 游戏活动
- ____FragmentQuest
- ____FragmentFight
- 类 MapLvl.kt
这是一款文本角色扮演游戏 Fragment Quest 显示了一段穿越不同地图(根据模板更改一个片段中的内容)的旅程文本、图片、导航按钮。如果地图上有怪物,则出现“战斗”按钮并打开回合制战斗FightFragment的片段(击中头部\腿部\身体保护头部\腿部\身体)。战斗结束后返回QuestFragment
类 MapLvl 填充 FightFragment 的内容 我需要将 QuestFragment 从 classLvl 更改为 FightFragment。怎么做?
它不起作用:类 MapLvl.kt:
class MapLevels(){ fun changeLvl (bind: FragmentQuestBinding,hero: Hero, activity: GameActivity,db: Maindb) { when (hero.mapLvl) { 1 -> MapLevels().mapLevel1(bind, activity, hero, db) 2 -> MapLevels().mapLevel2(bind, activity, hero,db) else -> {} } } fun mapLevel2 (bind: FragmentQuestBinding,activity: GameActivity,hero:Hero,db: Maindb) { bind.btnAtack.visibility= View.VISIBLE //the problem is here: bind.btnAtack.setOnClickListener { (activity as GameActivity).supportFragmentManager .beginTransaction() .replace(R.id.placeHolder,FightFragment.newInstance()) .commit() } } }错误: FragmentManager 尚未附加到主机
任务片段:
class QuestFragment : Fragment() { lateinit var bind:FragmentQuestBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View { bind = FragmentQuestBinding.inflate(inflater) return bind.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val hero = Hero() val db = Maindb.heroSetDb(requireActivity()) hero.extractHeroData(db,hero) scopeMain.launch { delay(50) MapLevels().changeLvl(bind,hero,GameActivity(),db) }如果您直接从片段进行调用,那么它会起作用:(但必须不是从片段而是从类)
任务片段:
class QuestFragment : Fragment() { lateinit var bind:FragmentQuestBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View { bind = FragmentQuestBinding.inflate(inflater) return bind.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val hero = Hero() val db = Maindb.heroSetDb(requireActivity()) hero.extractHeroData(db,hero) scopeMain.launch { delay(50) MapLevels().changeLvl(bind,hero,GameActivity(),db) } bind.btnAtack.setOnClickListener { (activity as GameActivity).supportFragmentManager .beginTransaction() .replace(R.id.placeHolder,FightFragment.newInstance()) .commit() }
【问题讨论】:
-
我不明白你想做什么。我们不“调用”片段。你也不能把一个片段改成另一个片段,真的。我想你的意思是你想显示 QuestFragment 的内容。但我不太确定。我建议您从用户的角度考虑这个问题。当用户启动应用程序时,他们应该在屏幕上看到什么?用户从那里做什么?用户接下来会看到什么?
-
@Code-Apprentice 这是一个文本RPG Fragment Quest 显示了一段穿越不同地图(根据模板更改一个片段中的内容)的旅程文本、图片、导航按钮。如果地图上有怪物,则出现“战斗”按钮并打开回合制战斗FightFragment的片段(击中头部\腿部\身体保护头部\腿部\身体)。战斗结束后返回QuestFragment
-
谢谢。请edit您的问题以包含这些详细信息。这完全可以使用片段管理器来实现。我看到你已经在
QuestFragment中使用它来更改为FightFragment。战斗结束后,你做类似的事情回到QuestFragment。 -
现在我更仔细地查看您的代码,我看到一条评论“问题出在这里:”。但问题到底是什么?单击此按钮时会发生什么?这个
MapLevels类是什么?在活动或片段类之外与按钮和其他视图进行交互是非常不寻常的。也许这是你问题的一部分?但是,在给您答复之前,我需要更多详细信息。
标签: android kotlin android-fragments fragment android-fragmentactivity