簡體   English   中英

如何從另一個 Activity 內的 onActivityResult 更改 Fragment 內的視圖?

[英]How to change Views inside a Fragment from an onActivityResult that is inside another Activity?

這看起來像一個重復的問題,但我已經嘗試了其他問題中給出的一些可能的解決方案,一段時間后我決定最好做一個新的。 我正在使用 Kotlin 在 Android 上制作一個活動,我用它來托管導航抽屜,在該活動中,有一個帶有一些按鈕的片段,當我點擊按鈕時,我會啟動掃描二維碼

CamaraQrIntegrator = IntentIntegrator(activity!!)
CamaraQrIntegrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE)
CamaraQrIntegrator.setPrompt("QrCodes")
CamaraQrIntegrator.setCameraId(0)
CamaraQrIntegrator.setBeepEnabled(false)
CamaraQrIntegrator.setOrientationLocked(false)
CamaraQrIntegrator.setBarcodeImageEnabled(false)
CamaraQrIntegrator.initiateScan()

因為 ZXing 要求我使用 IntentIntegrator 的父活動,所以 onActivityResult 位於活動而不是我正在使用的片段上

 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
/// I Try to access a progressbar inside the framgent 
}

這使得我無法訪問片段內的任何視圖,當嘗試使用 FindViewById 直接調用時,所有視圖都返回 null,在片段代碼中創建一個函數來訪問在 onCreateView 之后初始化的視圖,當我嘗試訪問查看它告訴我進度條為空

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
publicView = inflater.inflate(R.layout.fragment_principal, container, false)
 progressBar = publicView!!.findViewById(R.id.progressBarPrincipal)
return publicView
}
fun setProgressBarVisible(){
progressBar.visibility = View.VISIBLE
}
fun setProgressBarGone(){
progressBar.visibility = View.GONE
}

當我在活動上訪問 setProgressBarGone() 時,它告訴我 lateinit ProgressBar has not been initialized ,雖然片段沒有被破壞並且進度條確實在 OnCreateView 上初始化。

val MainFragment:Fragment = MainFragment()
val fragment = MainFragment().setProgressBarVisible()

我曾嘗試將片段上的視圖設為公開,但仍返回為 null ,我曾嘗試將進度條設為公開,但對於該活動它仍然為 null,這不僅發生在我嘗試在任何時候 onActivity 結果時訪問片段中的視圖返回為空。

我不知道該怎么做,任何幫助都會很好,請我真的想從一開始就想一些事情,所以我真的很感激修復的新解決方案,我所擁有的。 在這一點上,任何事情都會對我有所幫助。

在創建該 Fragment 對象並使用 craeted insatnace 在 onActivityResult 訪問片段方法上獲取片段實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM