android 需要帮助实现一个新的片段,应用程序崩溃,每当我尝试和导航到它

zujrkrfu  于 2023-05-27  发布在  Android
关注(0)|答案(1)|浏览(152)

我尝试添加一个条件语句,这样当用户单击除一之外的任何数量时,他们都会被带到片段,该片段将允许他们选择他们想要的每种口味的数量。

class StartFragment : Fragment() {
    private var binding: FragmentStartBinding? = null
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val fragmentBinding = FragmentStartBinding.inflate(inflater, container, false)
        binding = fragmentBinding
        return fragmentBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding?.startFragment = this

        binding?.apply {
            // Set up the button click listeners
            orderOneCupcake.setOnClickListener { orderCupcake(1) }
            orderSixCupcakes.setOnClickListener { orderCupcake(6) }
            orderTwelveCupcakes.setOnClickListener { orderCupcake(12) }
        }

    }
fun orderCupcake(quantity: Int): Boolean {
        sharedViewModel.setQuantity(quantity)
        if (sharedViewModel.hasNoFlavorSet()) {
            sharedViewModel.setFlavor(getString(R.string.vanilla))
        }
        findNavController().navigate(R.id.action_startFragment_to_flavorFragment)

        when (orderCupcake(6 or 12)) {
            -> findNavController().navigate(R.id.action_startFragment_to_flavor_picks)
        }

        return orderCupcake(quantity)

    }

override fun onDestroyView() {
        super.onDestroyView()
        binding = null
    }

    private val sharedViewModel: OrderViewModel by activityViewModels()
}
6jjcrrmo

6jjcrrmo1#

when (quantity) {

        1 -> findNavController().navigate(R.id.action_startFragment_to_flavorFragment)
        6, 12 -> findNavController().navigate(R.id.action_startFragment_to_flavor_picks)
    }

进行上述更改后,应用程序在我的device

中工作正常
在以前版本的解决方案中,当按下“six Cup cake”按钮时,应用程序会崩溃,因为quantity==1的导航路线被写入了when块,因此每当调用方法“orderCupCake”时,它首先尝试执行“FlavourFragment”而不是“FlavorPickFragment”的导航,这就是为什么它会抛出“IllegalArgumentException”的原因。需要“FlavourPickFragment”,但找到了“FlavourFragment”。
希望你有解决办法。

相关问题