Tabs In Xamarin Android

Introduction

In this blog, we are going to learn about how to add tabs in Xamarin Android app.

Solution

Here are the steps to add tabs in Android app.

Step 1

Create/ Open your Android Application in Visual Studio or Xamarin Studio.

Step 2

Now, open your layout file. In my case, it is main.axml and add the code given below. 

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:minWidth="25px"  
  7.     android:minHeight="25px">  
  8.     <TextView  
  9.         android:text="Medium Text"  
  10.         android:textAppearance="?android:attr/textAppearanceMedium"  
  11.         android:layout_width="match_parent"  
  12.         android:layout_height="wrap_content"  
  13.         android:id="@+id/textView1"  
  14.         android:gravity="center" />  
  15. </LinearLayout>   

Step 3

Open the MainActivity.cs file and add the code given below.

  1. protected override void OnCreate(Bundle bundle)  
  2.         {  
  3.             base.OnCreate(bundle);  
  4.   
  5.             SetContentView(Resource.Layout.Main);  
  6.             textView = FindViewById<TextView>(Resource.Id.textView1);  
  7.   
  8.             ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;  
  9.   
  10.             // Add the tabs to Action Bar  
  11.             AddTab("Tab One");  
  12.             AddTab("Tab Two");  
  13.         }   

In the code given above, in the first snapshot, we will set the Current view, then we are adding an Action Bar and in the last snapshot, we will add a method to add the tabs to the Action bar.

Step 4

Now, add the AddTab method into your main Activity. 

  1. private void AddTab(string tabText)  
  2.         {  
  3.             ActionBar.Tab tab = ActionBar.NewTab();  
  4.             tab.SetText(tabText);  
  5.             tab.TabSelected += OnTabSelected;  
  6.             ActionBar.AddTab(tab);  
  7.         }   

Step 5

Add the TabSelected listener, which is called on tab selection. 

  1. private void OnTabSelected(object sender, ActionBar.TabEventArgs args)  
  2.         {  
  3.             var CurrentTab = (ActionBar.Tab)sender;  
  4.   
  5.             if(CurrentTab.Position==0)  
  6.             {  
  7.                 textView.Text = "Tab One Selected";  
  8.             }  
  9.   
  10.             else  
  11.             {  
  12.                 textView.Text = "Tab Two Selected";  
  13.             }  
  14.         }   

In the code given above, the current tab will return the position of the selected tab and by using the position, we will change the text.

Here, you can also attach your custom view on the tab selection.

Output




Ebook Download
View all
Learn
View all