我有2个片段:MainGameFragment和PostGameFragment
启动MainActivity后,它会转到MainGameFragment,在其中我有一个带有动画的CustomView(它将是一个游戏)。
在CustomView内部,我会检查玩家是否输了每一帧,如果输了,我会调用一个方法。
当玩家失败并调用该方法时,我需要从CustomView内部更改为PostGameFragment。
我该怎么做?
我尝试使用supportFragmentManager,但得到以下信息:无法解析的参考:supportFragmentManager
这里是我的GameFragment代码,gameView是GameFrament内的CustomView的ID,Game是gameView的类,其中我具有onDraw方法和onLoseListener。
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
class GameFragment : Fragment() {
private var param1: String? = null
private var param2: String? = null
private var listener: OnFragmentInteractionListener? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view: View = inflater.inflate(R.layout.fragment_game, container, false)
gameView.onLoseListener = {
println("Testing..")
}
// Return the fragment view/layout
return view
}
fun onButtonPressed(uri: Uri) {
listener?.onFragmentInteraction(uri)
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is OnFragmentInteractionListener) {
listener = context
} else {
throw RuntimeException(context.toString() + " must implement OnFragmentInteractionListener")
}
}
override fun onDetach() {
super.onDetach()
listener = null
}
interface OnFragmentInteractionListener {
fun onFragmentInteraction(uri: Uri)
}
companion object {
@JvmStatic
fun newInstance() =
GameFragment().apply {
arguments = Bundle().apply {
}
}
}
}
答案 0 :(得分:0)
典型的模式是从内部View
向您的invoke
添加回调(侦听器),以将事件发信号到外部代码。
class CustomView @JvmOverloads constructor(
context: Context?,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
var onLoseListener: () -> Unit = {
// do nothing by default
}
// to signal the listener call -> `onLoseListener.invoke()`
}
您有CustomView
的任何地方:
class CustomFragment : Fragment(){
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
//... inflate
// assuming you have `val customView : CustomView`
// setting up the listener:
customView.onLoseListener = {
//do something on the listener being invoked by the CustomView
}
return yourInflatedLayout
}
}