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.
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:minWidth="25px"
- android:minHeight="25px">
- <TextView
- android:text="Medium Text"
- android:textAppearance="?android:attr/textAppearanceMedium"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/textView1"
- android:gravity="center" />
- </LinearLayout>
Step 3
Open the MainActivity.cs file and add the code given below.
- protected override void OnCreate(Bundle bundle)
- {
- base.OnCreate(bundle);
- SetContentView(Resource.Layout.Main);
- textView = FindViewById<TextView>(Resource.Id.textView1);
- ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;
- // Add the tabs to Action Bar
- AddTab("Tab One");
- AddTab("Tab Two");
- }
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.
- private void AddTab(string tabText)
- {
- ActionBar.Tab tab = ActionBar.NewTab();
- tab.SetText(tabText);
- tab.TabSelected += OnTabSelected;
- ActionBar.AddTab(tab);
- }
Step 5
Add the TabSelected listener, which is called on tab selection.
- private void OnTabSelected(object sender, ActionBar.TabEventArgs args)
- {
- var CurrentTab = (ActionBar.Tab)sender;
- if(CurrentTab.Position==0)
- {
- textView.Text = "Tab One Selected";
- }
- else
- {
- textView.Text = "Tab Two Selected";
- }
- }
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


Neelam PrajapatiPosted Jul 25, 2018, 3:29 AM
Throwing null reference exception in action bar
Ayappan AlagesanPosted Mar 15, 2018, 7:07 AM
Hi sir I need tab control like windows tab contol style, with close button and pin button.can you help me.in Xamarin forms ..ios ipad
Megha TiwariPosted Jan 3, 2018, 7:52 AM
Hi, I have created Tab successfully but when I try with "AppCompatActivity" I have an exception error [Unhandled Exception:Java.Lang.IllegalStateException: ]Can you suggest me How work with AppCompatActivity for creating tab ???