Используйте supportFragmentManager внутри CustomView внутри Fragment - PullRequest
1 голос
/ 09 июля 2019

У меня есть 2 фрагмента: MainGameFragment и PostGameFragment

Когда запускается MainActivity, он переходит в MainGameFragment, где у меня есть CustomView с анимацией (это будет игра).

Внутри CustomViewЯ проверяю каждый кадр, если проигрыватель проигрывает, когда он проигрывает, я вызываю метод.

Мне нужно перейти на PostGameFragment изнутри CustomView, когда проигрыватель проигрывает и вызывается метод.

КакМогу ли я это сделать?

Я пытался использовать supportFragmentManager, но я получаю следующее: Неразрешенная ссылка: supportFragmentManager

Вот мой код GameFragment, gameView - это идентификатор CustomView, который находится внутри GameFrament, и Game isкласс для 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 {

            }
        }
}

}

1 Ответ

0 голосов
/ 10 июля 2019

Типичным шаблоном является добавление обратного вызова (слушателя) к вашему 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
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...