[英]How to pass data between two fragments without any buttons?
我在底部導航之間移動了兩個片段。 我想在它們之間傳遞沒有任何按鈕的數據。 看起來是這樣的:在第一個片段中,我在編輯文本中包含字符串,然后轉到另一個片段,我想將此字符串傳遞給該片段中的文本視圖。
第一個片段:
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;
}
}
這是有關如何與片段進行通信的官方文檔 。 有多種方法可以做到這一點。 您可以使用接口方法,可以使用像GreenRobot這樣的EventBus,也可以使用LiveData 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.