Hello,
Welcome to our Microsoft Q&A platform!
I working with two or three pages under the same Activity and I want to slide between them with finger slide movement.
Try using Fragment
to display the 'pages' in the same Activity. You could combine TabLayout
with ViewPager
to achieve sliding tab navigation.
<LinearLayout ...
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<androidx.viewpager.widget.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Create a custom adapter for the ViewPager to populate the data. You could inflate the layout.xml for the fragment. Here is the sample code, please check it.
public class MainActivity : AppCompatActivity
{
TabLayout tabLayout;
ViewPager pager;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.activity_main);
tabLayout = FindViewById<TabLayout>(Resource.Id.tabLayout);
pager = FindViewById<ViewPager>(Resource.Id.pager);
PagerAdapter adapter = new PagerAdapter(this.SupportFragmentManager);
adapter.AddFragment(new FragmentA(), "FragmentA");
adapter.AddFragment(new FragmentB(), "FragmentB");
adapter.AddFragment(new FragmentC(), "FragmentC");
pager.Adapter = adapter;
adapter.NotifyDataSetChanged();
tabLayout.SetupWithViewPager(pager);
}
}
//custom adapter
public class PagerAdapter : FragmentStatePagerAdapter
{
public List<AndroidX.Fragment.App.Fragment> fragments = new List<AndroidX.Fragment.App.Fragment>();
public List<string> fragmentTitles = new List<string>();
public PagerAdapter(AndroidX.Fragment.App.FragmentManager fm) : base(fm)
{
}
public void AddFragment(AndroidX.Fragment.App.Fragment fragment, string title)
{
fragments.Add(fragment);
fragmentTitles.Add(title);
}
public override int Count => fragments.Count;
public override AndroidX.Fragment.App.Fragment GetItem(int position)
{
return fragments[position];
}
public override ICharSequence GetPageTitleFormatted(int position)
{
return new Java.Lang.String(fragmentTitles[position]);
}
}
//custom fragment
public class FragmentA : AndroidX.Fragment.App.Fragment
{
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.Inflate(Resource.Layout.fragment_a_layout, container, false);
}
}
Here is the working screenshot:
Related doc: https://learn.microsoft.com/en-us/xamarin/android/user-interface/controls/view-pager/viewpager-and-views
Best Regards,
Jarvan Zhang
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.