FirstFragment.java
public class FirstFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
CategoryModel[] list = {new CategoryModel(1, "Category 1")
, new CategoryModel(2, "Category 2")
, new CategoryModel(3, "Category 3")
, new CategoryModel(4, "Category 4")
, new CategoryModel(5, "Category 5")};
FirstFragmentDirections.actionFirstFragmentToSecondFragment(list);
return inflater.inflate(R.layout.fragment_first, container, false);
}
}
SecondFragment.java
public class SecondFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
CategoryModel[] list = SecondFragmentArgs.fromBundle(getArguments()).getCategories();
return inflater.inflate(R.layout.fragment_second, container, false);
}
}
CategoryModel.java
public class CategoryModel {
private final int id;
private final String name;
public CategoryModel(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
main_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@ id/main_navigation"
app:startDestination="@id/firstFragment">
<fragment
android:id="@ id/firstFragment"
android:name="com.test.ttt.FirstFragment"
tools:layout="@layout/fragment_first">
<action
android:id="@ id/action_firstFragment_to_secondFragment"
app:destination="@id/secondFragment" />
</fragment>
<fragment
android:id="@ id/secondFragment"
android:name="com.test.ttt.SecondFragment"
tools:layout="@layout/fragment_second">
<argument
android:name="categories"
app:argType="com.test.ttt.CategoryModel[]" />
</fragment>
</navigation>
I'm trying to send the categories from the first fragment to the second fragment but I got this error during run the app

I searched carefully before posting this question but I did not reach to any solution...............................
uj5u.com熱心網友回復:
您可以在 NavController 的 navigate() 方法中將 bundle 作為第二個引數傳遞,與 Intent 相同。
使用 Kotlin:
fun Activity.open(destination: Int, params: HashMap<String, Any?>) {
try {
val navController = findNavController(this, id of navigation graph container) // Mine is R.id.fragmentsContainer
navController.navigate(destination, params.toBundle())
} catch (e: Exception) {
e.printStackTrace()
}
}
您可以使用上述快捷方式進行片段導航,只需傳遞目標片段 id 和 hashmap/用 bundle 替換它)
使用 Java:
void open(Integer destination, Bundle bundle) {
try {
NavController navController = Navigation.findNavController(this, id of navigation graph container); // Mine is R.id.fragmentsContainer
navController.navigate(destination, bundle);
} catch (e:Exception){
e.printStackTrace()
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/444721.html
標籤:android android-fragments android-architecture-components android-architecture-n
