如何从 Android 中的不同 class 访问片段中定义的函数?

How can I reach a function defined in fragment from different class in Android?

我有一个应用程序,它有一个片段,旨在显示通过单击按钮选择的 pdf。我已经实现了这个方法,但是如何在我应该调用这个方法的不同 class 中调用这个片段函数?

此方法在 class 中定义,其中我尝试访问片段函数:

fun importPdf(fragment: Fragment, label: DocumentLabel?) {
   val pickPdfDocument =
   fragment.registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
    if (uri == null) {
     KycEventBus.post(DocumentImportEvent(false))
    }
    uri?.let {
     Log.d(TAG, "ImportPdf - ActivityResultContracts.GetContent() successful.")

     PdfViewer.displayFromUri(it) // Here is where I try to reach

     val documentPdfFile = DocumentUtil.saveUriAsTemporary(
     context = fragment.requireContext(),
     uri = uri,
     subFolder = cacheFolderName + File.separator + cachePdfFolderName,
     label = label?.name,
     documentType = DocumentUtil.DocumentType.PDF
    )

    documentPhotoFilePath = documentPdfFile.path
    Log.d(TAG, "documentPhotoFile path: " + documentPdfFile.path)
    KycEventBus.post(DocumentImportEvent(true))
          }
       }
    pickPdfDocument.launch("application/pdf")
 }

此函数在片段中:

public fun displayFromUri(uri: Uri) {
        pdfFilePath = getFileName(uri)
        pdfView_fragment_pdfviewer!!.fromUri(uri)
            .defaultPage(pageNumber)
            .onPageChange(this)
            .enableAnnotationRendering(true)
            .onLoad(this)
            .scrollHandle(DefaultScrollHandle(context))
            .spacing(10) // in dp
            .onPageError(this)
            .load()
}

创建此 class 的实例并调用该函数。

伴随对象

内添加片段的方法
companion object{

   fun displayFromUri(uri: Uri) {
        pdfFilePath = getFileName(uri)
        pdfView_fragment_pdfviewer!!.fromUri(uri)
            .defaultPage(pageNumber)
            .onPageChange(this)
            .enableAnnotationRendering(true)
            .onLoad(this)
            .scrollHandle(DefaultScrollHandle(context))
            .spacing(10) // in dp
            .onPageError(this)
            .load()
}

}

然后在class中调用:

displayFromUri(Uri.parse("url"))

如果您希望它更灵活,请考虑使用实时数据、rxJava 或协程 API,如下所示:

private val _importResult = MutableLiveData<Uri>()
val importResult: LiveData<Uri> = _importResult
fun importPdf(fragment: Fragment, label: DocumentLabel?): LiveData<Uri> {
  ....
  _importResult.value = uri
}

然后在您希望从中调用方法的片段中观察此实时数据:

classToCallFragmentMethodFromInstance.importResult.observe(viewLifecycleObserver, Observer{
  // call your method here
})

使用这种方法,您可以在 class 中解耦您的代码,您希望从片段中调用方法,从实际片段中调用方法,因此多个片段可以使用此 class。