How do you switch between two pages on Android?
There are various methods in Android for implementing page transitions, and here are some commonly used ones:
- Switching pages using Intent: By creating an Intent object and specifying the class name of the page to switch to, then calling the startActivity method to implement the page switch.
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
startActivity(intent);
- Switching pages using Fragments: manage different pages as Fragments, and use the replace method of FragmentTransaction to switch pages by replacing the current Fragment.
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, new TargetFragment());
transaction.commit();
- Switching pages using ViewPager: You can set multiple pages as children of the ViewPager, and switch between them by using the ViewPager.setCurrentItem method to set the currently displayed page.
ViewPager viewPager = findViewById(R.id.viewPager);
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
viewPager.setCurrentItem(1); // 切换到第二个页面
- Utilizing Activity transition animations: You can create smooth transition effects between pages by setting transition animations for Activities when switching pages.
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
These are several commonly used methods to achieve page switching in Android. Choose different methods based on specific needs and scenarios to achieve the desired page switching effect.