如何使用 Androidx 在 Kotlin 中获取 DialogFragment 的 FragmentManager?

How to get a FragmentManager for DialogFragment in Kotlin using Androidx?

我正在学习讲师使用 Android 支持库 v7 的教程。在我的应用程序中,我使用的是 androidx 版本(如 Android 开发者网站上所建议)。当我按照指示键入代码行时,Android Studio 在我尝试获取 FragmentManager 的部分代码上添加了删除线,并说:"getter for fragmentManager: FragmentManager! is deprecated. Deprecated in Java." 我搜索了很多人们有类似问题的帖子问题,但提供的解决方案不适用于我的情况。一些用户的支持库版本不匹配,而其他用户在 gradle 文件中没有正确的依赖项。据我所知,这些问题不适用于此处。

根据 FragmentManager 的 androidx 文档,它指出,"Your activity must derive from FragmentActivity to use this. From such an activity, you can acquire the FragmentManager by calling FragmentActivity#getSupportFragmentManager." 但是,我没有使用 Activity,代码位于内部 class扩展 RecylcerView.ViewHolder class 嵌套在 class 扩展 RecyclerView.Adapter 中。 android 支持库 v7 是我唯一的选择吗?

RecyclerView 适配器Class:

import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.e_product_row.view.*

import androidx.fragment.app.DialogFragment  // greyed out as "unused import directive"
import androidx.fragment.app.FragmentManager // greyed out as "unused import directive"


class EProductAdapter(var context: Context, var arrayList : ArrayList<EProduct>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
    val productView = LayoutInflater.from(context).inflate(R.layout.e_product_row, parent, false)
    return ProductViewHolder(productView)
  }

  override fun getItemCount(): Int {
    return arrayList.size
  }

  override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    // downcast holder to ProductViewHolder
    (holder as ProductViewHolder).initializeRowComponents(arrayList.get(position).id,
                                                          arrayList[position].name,
                                                          arrayList[position].price,
                                                          arrayList[position].picture)
  }

  inner class ProductViewHolder(productView: View) : RecyclerView.ViewHolder(productView) {
    fun initializeRowComponents(id: Int, name: String, price: Int, pictureName: String) {
      itemView.txt_id.text = id.toString()
      itemView.txt_name.text = name
      itemView.txt_price.text = price.toString()
      var pictureUrl = "http://192.168.0.21/OnlineStoreApp/osimages/$pictureName"
      pictureUrl = pictureUrl.replace(" ", "%20")
      Picasso.get().load(pictureUrl).into(itemView.img_product)

      // initialize add item imageView
      itemView.img_add_item.setOnClickListener {
        var amountFragment = AmountFragment()
        var fragmentManager = (itemView.context as Activity).fragmentManager // fragmentManager strikethrough text
         amountFragment.show(fragmentManager, "TAG") // show function cannot be called with arguments supplied and won't compile
      }
    }
  }
}

DialogFragment class:

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment

class AmountFragment : DialogFragment() {
  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                            savedInstanceState: Bundle? ): View? {
    return inflater.inflate(R.layout.fragment_amount, container, false)
  }
}

build.gradle(模块:应用)

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"

    defaultConfig {
        applicationId "com.bryontaylor.onlinestoreapp"
        minSdkVersion 24
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.android.volley:volley:1.1.1'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.squareup.picasso:picasso:2.71828'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'androidx.fragment:fragment:1.2.4'
    implementation 'androidx.fragment:fragment-ktx:1.2.4'
}

According to the androidx documentation for FragmentManager, it states, "Your activity must derive from FragmentActivity to use this. From such an activity, you can acquire the FragmentManager by calling FragmentActivity#getSupportFragmentManager." However, I am not using an Activity

是的,你是:

var fragmentManager = (itemView.context as Activity).fragmentManager

唯一的问题是您正在转换为根 Activity 类型并使用已弃用的 getFragmentManager()。您需要完全按照文档状态进行操作:使用 FragmentActivitygetSupportFragmentManager():

var fragmentManager = (itemView.context as FragmentActivity).supportFragmentManager

您的 show() 调用将起作用,因为您传递的是正确的片段管理器类型。

希望对您有所帮助!