0

我正在尝试在我的底部工作表中重用已经创建的片段,为此我使用下面的代码。

class SummaryBottomSheet: BottomSheetDialogFragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val bundle = Bundle()
        val diskOnly =false;

        val ft: androidx.fragment.app.FragmentTransaction = childFragmentManager.beginTransaction()
        ft.replace(R.id.reader_placeholder, ReaderFragment())
        ReaderFragment().arguments = Bundle().apply {
            bundle.putBoolean("diskonly",false)
        }
        ft.commit()
    }
}

现在我将捆绑的参数发送到我想在 bootomsheet 片段中拥有的片段。并且该片段还从导航器 navArgs() 接收参数,但这在我的底页中没有发生,因为现在我不是在导航而是在底页中使用相同的片段。

我正在重用的片段是:

lass ReaderFragment : BaseFragment(R.layout.fragment_reader), PageletActionMediator {

    private val args: ReaderFragmentArgs by navArgs()
    private val viewModel: ReaderViewModel by viewModels()
    private val activityViewModel: MainActivityViewModel by activityViewModels()

    private lateinit var recyclerView: RecyclerView
    private lateinit var viewAdapter: PageletListAdapter
    private lateinit var viewManager: LinearLayoutManager

    override fun onCreate(savedInstanceState: Bundle?) {
        Timber.d("created ")


        val arguments = requireArguments()
        val diskOnly = arguments.getBoolean("diskonly")
        shortAnimationDuration = resources.getInteger(android.R.integer.config_shortAnimTime)
 
if(arguments){
        slug?.let { slug ->
            viewModel.initWithSlug(slug, diskOnly)
            return
        }}
else args?.let{
slug ->
            viewModel.initWithSlug(slug, diskOnly)
            return
}
    }

我的应用程序每次都因错误而崩溃:

java.lang.IllegalStateException: Fragment ReaderFragment{5b3fc12} (7d5de6e0-3258-468c-8db4-d201b4c3f672) id=0x7f090346} does not have any arguments.
                         E      at androidx.fragment.app.Fragment.requireArguments(Fragment.java:679)
                         E      at com.pratilipi.comics.ui.reader.ReaderFragment.onCreate(ReaderFragment.kt:91)
                         E      at androidx.fragment.app.Fragment.performCreate(Fragment.java:2684)
    ```


4

1 回答 1

1

您没有在replace调用中实际使用的片段上设置参数:

// Here you create a fragment add use it in replace()
ft.replace(R.id.reader_placeholder, ReaderFragment())

// Here you create a *second* fragment, set its arguments,
// then do nothing with it.
ReaderFragment().arguments = Bundle().apply {
    bundle.putBoolean("diskonly",false)
}

相反,您需要在使用的片段上设置参数replace

val fragment = ReaderFragment()
fragment.arguments = Bundle().apply {
    bundle.putBoolean("diskonly",false)
}
ft.replace(R.id.reader_placeholder, fragment)
于 2021-08-09T04:33:33.203 回答