簡體   English   中英

使用Bundle將文件從Activity傳遞到片段

[英]Passing a file from Activity to fragment using Bundle

好的,所以我正在嘗試將文件管理器(Activity)中的任何文件傳遞給片段。 這是我的代碼:

               Bundle bundle = new Bundle ();
                    bundle.putString ("File", chosenFile);
                    Intent intent = new Intent (getApplicationContext (), UploadFragment.class);
                    intent.putExtras (bundle);
                    startActivity (new Intent (FileExplore.this, UploadFragment.class));

應用程序在Logcat中崩潰是無法找到顯式活動類的狀態。 然后,這給了我一行代碼發生錯誤的那一行,即startActivity(new Intent(.....)。是因為我沒有將Intent從Activity正確地發送到Fragment而導致的錯誤?

在“片段”中,button.setOnclickListener()下有以下代碼。

Intent intent = new Intent (getActivity (), FileExplore.class);
            startActivity (intent);

首先,您無法使用Intent創建片段或向其發送數據。

您可以通過調用以下getFragmentManager().beginTransaciton().add(R.id.id_of_container, new UploadFragment(), false).commit();在活動中放入一個片段: getFragmentManager().beginTransaciton().add(R.id.id_of_container, new UploadFragment(), false).commit();

如果要將數據從活動傳遞到片段,則可以使用setArgument()方法在片段創建時進行setArgument() ,例如:

Bundle bundle = new Bundle ();
bundle.putString ("File", chosenFile);

UploadFragment fragment = new UploadFragment();
fragment.setArguments(bundle);

getFragmentManager().beginTransaction().add(R.id.fragment_container, fragment).commit();

暫無
暫無

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

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