Search code examples
javaandroidandroid-tabs

Android tab clicked


I'm trying to apply TABs to my Android layout. How could I identify which tab was clicked?

I have an android tab layout made this way:

package com.truiton.designsupporttabs;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class TabFragment2 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.tab_fragment_2, container, false);
    }
}

With the layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Tab 2"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

</RelativeLayout>

I do not know how to identify that a tab like the above example was clicked.


Solution

  • Having as a principle that your code was based on the Truiton tutorial, just follow how they identify the clicks.

    package com.truiton.designsupporttabs;
    
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentStatePagerAdapter;
    
    public class PagerAdapter extends FragmentStatePagerAdapter {
        int mNumOfTabs;
    
        public PagerAdapter(FragmentManager fm, int NumOfTabs) {
            super(fm);
            this.mNumOfTabs = NumOfTabs;
        }
    
        @Override
        public Fragment getItem(int position) {
    
            switch (position) {
                case 0:
                    TabFragment1 tab1 = new TabFragment1();
                    return tab1;
                case 1:
                    TabFragment2 tab2 = new TabFragment2();
                    return tab2;
                case 2:
                    TabFragment3 tab3 = new TabFragment3();
                    return tab3;
                default:
                    return null;
            }
        }
    
        @Override
        public int getCount() {
            return mNumOfTabs;
        }
    }
    

    This should work!