0

我的活动是...

   private var preso: ClientResultPresentationFragment? = null
   private var presoHelper: PresentationHelper? = null

   private val presoListener = object: PresentationHelper.Listener{
        override fun initSecondDisplay(display: Display?) {
            Log.d("preso", "initSecondDisplay()")
            preso = MytPresentationFragment.newInstance(this@MyActivity, display)
            preso!!.show(fragmentManager, PRESO) // PRESO is a static value.
        }

        override fun clearPreso(switchToInline: Boolean) {
            if (preso != null) {
                preso!!.dismiss()
                preso = null
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_my)

        // Must open second display at the same time.
        onCreatePreso()

        refinedResultData = intent.extras!!.getParcelable(RESULT_DATA)
        Log.d("result", "${resultData.toString()}")
        init(resultData!!)
    }

    private fun init(data: ResultData){
        initView(data)
        preso!!.syncData(data)
    }

    private initView(data: ResultData){
        // TODO: initViews...
    }

    private fun onCreatePreso(){
        presoHelper = PresentationHelper(this, presoListener)
        presoHelper!!.enable()
    }

    override fun onResume() {
        super.onResume()
        presoHelper?.onResume()
    }

    override fun onPause() {
        presoHelper?.onPause()
        super.onPause()
    }

我的演示片段是...

    var mView: View? = null

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        Log.d("preso", "onCreateView()")
        
        mView = LayoutInflater.from(context).inflate(R.layout.fragment_my, container, false)
        return mView
    }

    fun syncData(data: ResultData){
        Log.d("preso", "syncData()->${data.toString()}")
        initView()

        // return >>> here...

        mView!!.tv_title.text = "${data.title}" // <<< crash here >>>
        // TODO: set initial data
    }

    fun initView(){
        // initViews...
    }

    companion object {
        fun newInstance(context: Context?, display: Display?): MyPresentationFragment {
            val frag = MyPresentationFragment()
            
            frag.setDisplay(context, display)

            return frag
        }
    }

日志是...

"resultData.toString()"
initSecondDisplay()
"syncData()->${data.toString()}"
crash------------------

如果我只是在 Presentation Fragment 的 syncData() 中取消注释返回部分(它不会访问视图)

"resultData.toString()"
initSecondDisplay()
"syncData()->${data.toString()}"
onCreateView()

因此,syncData()比 更早地调用onCreateView()。我应该怎么办?我后来搬家preso!!.syncData()preso!!.show(fragmentManager, PRESO),还是一样。

4

1 回答 1

0

由于FragmentManager操作是异步的,你应该从你的片段发送一个回调到片段中的活动,OnViewCreated或者也许OnResume然后才将数据从活动发送到片段。或者您可以只使用ViewModel并将LiveData您的数据提供给片段

于 2020-12-03T06:23:53.490 回答