如何在两个片段之间传递数据而没有任何按钮?

时间:2019-01-23 22:29:12

标签: android android-fragments android-intent data-binding

我在底部导航之间移动了两个片段。我想在它们之间传递没有任何按钮的数据。看起来像这样:在第一个片段中,我在编辑文本中包含字符串,然后我将转到另一个片段,我想将此字符串传递给该片段中的文本视图。

第一个片段:

 public class TodayFragment extends Fragment {


@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    FragmentTodayBinding fragmentTodayBinding = DataBindingUtil.inflate(inflater,R.layout.fragment_today, null, false);
    View view = fragmentTodayBinding.getRoot();
    TodayViewModel todayViewModel = ViewModelProviders.of(this).get(TodayViewModel.class);
    fragmentTodayBinding.setTodayViewModel(todayViewModel);

    fragmentTodayBinding.setTodayFragmentInterface(new TodayFragmentInterface() {
        @Override
        public void onSearchClick(View v) {
            todayViewModel.getCity();
        }
    });

    todayViewModel.getWeather().observe(getViewLifecycleOwner(), new Observer<Weather>() {
        @Override
        public void onChanged(Weather weather) {
            fragmentTodayBinding.windTextView.setText("Wind: " + String.valueOf(weather.getWind().getSpeed()) + " km/h");
            fragmentTodayBinding.humidityTextView.setText("Humidity: " + weather.getMain().getHumidity() + " %");
            fragmentTodayBinding.pressureTextView.setText("Pressure: " + weather.getMain().getPressure() + " mBar");
            Double temp = weather.getMain().getTemp();
            DecimalFormat df = new DecimalFormat("#0.0");
            fragmentTodayBinding.tempTextView.setText(df.format(temp) + " ℃");
            String desc = weather.getDescription();
            String desc2 = Character.toString(desc.charAt(0)).toUpperCase()+desc.substring(1);
            fragmentTodayBinding.conditionTextView.setText(desc2);
            Glide.with(TodayFragment.this).load(weather.getIconUrl()).into(fragmentTodayBinding.iconImageView);
        }
    });

    return view;
}

第二个片段:

public class HourlyFragment extends Fragment {


@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    FragmentHourlyBinding fragmentHourlyBinding = DataBindingUtil.inflate(inflater,R.layout.fragment_hourly, null, false);
    View view = fragmentHourlyBinding.getRoot();
    HourlyViewModel hourlyViewModel = ViewModelProviders.of(this).get(HourlyViewModel.class);

    List<String> data = new ArrayList<>();

    RecyclerView recyclerView = view.findViewById(R.id.recycler_view);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    final RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(getActivity(), data);
    recyclerView.setAdapter(recyclerViewAdapter);


    return view;
}

}

1 个答案:

答案 0 :(得分:0)

这是有关如何与片段进行通信的官方docs。有多种方法可以做到这一点。您可以使用接口方法,也可以使用GreenRobot之类的EventBus,也可以使用LiveData