在上一节 中,我们简单使用了 Jetpack中的 Navigation , NavGraph, NavHost,Fragment 来实现页面之间的切换,但并没有涉及到页面之间如何传递数据?本节讲述 如何通过 Bundle 在Fragement中 传递数据
效果图
实现步骤 准备两个Fragment 界面 以及对应的类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 public class HomeFragment extends Fragment { public HomeFragment () { } @Override public void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState); } @Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_home, container, false ); } @Override public void onActivityCreated (@Nullable Bundle savedInstanceState) { super .onActivityCreated(savedInstanceState); getView().findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v) { EditText editText = getView().findViewById(R.id.edit); String string = editText.getText().toString().trim(); if (TextUtils.isEmpty(string)) { return ; } NavController controller = Navigation.findNavController(v); Bundle bundle = new Bundle(); bundle.putString("my_name" , string); controller.navigate(R.id.action_homeFragment_to_detailFragment, bundle); } }); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 public class DetailFragment extends Fragment { public DetailFragment () { } @Override public void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState); } @Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_detail, container, false ); } @Override public void onActivityCreated (@Nullable Bundle savedInstanceState) { super .onActivityCreated(savedInstanceState); TextView textView = getView().findViewById(R.id.textView); String name = getArguments().getString("my_name" , "default_name" ); textView.setText(name); } }
准备NavGraph 右击res
–New
–Android Resource File ,在Resource Type中 选择 Navigation
准备NavHost 在Activity _main 中 放置一个,NavHostFragement
编写Fragment中 点击事件 详见 上述代码
总结 主要记住 以下代码
传值 : 1 2 3 4 NavController controller = Navigation.findNavController(v); Bundle bundle = new Bundle(); bundle.putString("my_name" , string); controller.navigate(R.id.action_homeFragment_to_detailFragment, bundle);
取值 1 String name = getArguments().getString("my_name" , "default_name" );