У меня есть Activity
, который содержит основной Fragment
, который затем содержит ViewPager
и TabLayout
.Я реализовал NavigationDrawer
i my MainActivity
и хочу изменить viewPager.setCurrentItem
, когда пользователь щелкает элемент в NavigationDrawer
.
Как я могу передать данные из NavigationDrawer
вмой MainActivity
, к ViewPager
, который находится в моем Fragment
?
Основная деятельность:
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
//TODO: handle the item clicks in navDrawer
switch (menuItem.getItemId()) {
case R.id.nav_home:
// Here I want to call viewPager.setCurrentItem(0), but I cannot call this from here.
Toast.makeText(NITrafficActivity.this, "Home!", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_cctv:
Toast.makeText(NITrafficActivity.this, "CCTV Cameras", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_future_roadworks:
Toast.makeText(NITrafficActivity.this, "Future Roadworks", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_journey_times:
Toast.makeText(NITrafficActivity.this, "Journey Times", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_speed_cameras:
Toast.makeText(NITrafficActivity.this, "Speed Cameras", Toast.LENGTH_SHORT).show();
break;
}
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
Основной фрагмент:
public class TrafficTabsFragment extends Fragment implements OnBackPressedHandler {
private MyViewModel viewModel;
private SearchView searchView;
private TabLayout tabLayout;
private ViewPager viewPager;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
viewModel = ViewModelProviders.of(requireActivity()).get(MyViewModel.class);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_traffic_tabs, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final List<Pair<String, Fragment>> tabs = CollectionsKt.arrayListOf(
new Pair<String, Fragment>(getString(R.string.roadworks, 0), RoadworksFeedFragment.newInstance()),
new Pair<String, Fragment>(getString(R.string.incidents, 0), IncidentsFeedFragment.newInstance())
);
tabLayout = view.findViewById(R.id.main_tab_layout);
viewPager = view.findViewById(R.id.main_view_pager);
viewPager.setAdapter(new TrafficTabsAdapter(getChildFragmentManager(), tabs));
tabLayout.setupWithViewPager(viewPager);
monitorFilterCount(viewModel.roadworksFilterCount, 0, R.string.roadworks);
monitorFilterCount(viewModel.incidentsFilterCount, 1, R.string.incidents);
}