آموزش TabLayout با استفاده از ViewPager و Fragments

سلام دوستان با آموزش TabLayout با استفاده از ViewPager و Fragments باز بازگشتیم خب اصلا این Tablayout به چه دردی میخوره ؟! در جواب به این سوال یکسری از متدها برای پیاده سازی متریال دیزان استفاده از Tablayout و دسته بندی اکتیویتی های مختلف است پس دو کار برای ما انجام می دهد و استفاده از آن هم مثل آب خوردن است زیاد دیگه سرتون رو درد نمیارم میرم بخش کد.در ادامه با ما همراه باشید. برای استفاده از Tablayout نیاز به اضافه کردن Design Support در فایل گریدل هست مثل همیشه باید قند شکنمون رو روشن کنیم علتش رو هم در این پست گفته ایم می توانید آن را مطالعه کنید
خب پس فایل Gradle را باز کرده و خط زیر رو در آن قرار دهید.

    compile 'com.android.support:appcompat-v7:23.2.0'

فقط دوستان توجه کنند باید Desgin مربوط به Sdk که شما نصب کردید را قرار دهید در این جا ما از Sdk ورژن 23 استفاده کرده ایم ممکن است برای شما به طور مثال 25 باشد پس تغییرات رو خودتان اعمال کنید.
در اینجا ما باید سه فایل xml ایجاد کرده این سه فایل همان View های ما برای ViewPager خواهند بود و اسم آنها به ترتیب tab.xml , tab2.xml و Tab3.xml خواهند بود.
تب اول

<?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 1"
        android:textAppearance="?android:attr/textAppearanceLarge"/>
</RelativeLayout>

تب دوم

<?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>

تب سوم

<?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 1"
        android:textAppearance="?android:attr/textAppearanceLarge"/>
</RelativeLayout>

خب تا اینجا خوب پیش رفتیم حالا باید 3 تا کلاس جاوا مرتبط با این 3 Layout که ساخته شده بسازیم همانند زیر می شود کلاس های ما.
tab1.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
 * Created by Jfp on 2/3/2017.
 */
//Our class extending fragment
public class Tab1 extends Fragment {
    //Overriden method onCreateView
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //Returning the layout file after inflating
        //Change R.layout.tab in you classes
        return inflater.inflate(R.layout.tab, container, false);
    }
}

tab2.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
 * Created by jfp on 2/3/2017.
 */
//Our class extending fragment
public class Tab1 extends Fragment {
    //Overriden method onCreateView
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //Returning the layout file after inflating
        return inflater.inflate(R.layout.tab2, container, false);
    }
}

tab3.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
 * Created by jfp on 2/3/2017.
 */
//Our class extending fragment
public class Tab1 extends Fragment {
    //Overriden method onCreateView
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //Returning the layout file after inflating
        return inflater.inflate(R.layout.tab3, container, false);
    }
}

حال زمان ساخت Pager.java می رسد این کلاس ارتباط بین ViewPager را با  Fragment های ساخته شده برقرار می کند
فایل Pager به شکل زیر می شود.

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
 * Created by تبح on 2/3/2017.
 */
//Extending FragmentStatePagerAdapter
public class Pager extends FragmentStatePagerAdapter {
    //integer to count number of tabs
    int tabCount;
    //Constructor to the class
    public Pager(FragmentManager fm, int tabCount) {
        super(fm);
        //Initializing tab count
        this.tabCount= tabCount;
    }
    //Overriding method getItem
    @Override
    public Fragment getItem(int position) {
        //Returning the current tabs
        switch (position) {
            case 0:
                Tab1 tab1 = new Tab1();
                return tab1;
            case 1:
                Tab2 tab2 = new Tab2();
                return tab2;
            case 2:
                Tab3 tab3 = new Tab3();
                return tab3;
            default:
                return null;
        }
    }
    //Overriden method getCount to get the number of tabs
    @Override
    public int getCount() {
        return tabCount;
    }
}

زمان حذف Actionbar می رسد وارد فایل style.xml شده سپس تغییرات زیر را اعمال کنید.

<resources>
    <!-- Base application theme. -->
    <!-- changing it to no actionbar -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>

 
خب کلاس های خودمان رو هم ساختیم حالا باید صفحه اصلی برنامه رو بسازیم که این کلاس ها و View ها در آن نمایش داده خواهند شد
فایل Activiy_Main.xnl همانند زیر می شود در آن View Pager و Tab را قرار داده ایم

<LinearLayout
    android:id="@+id/main_layout"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <!-- our toolbar -->
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
    <!-- our tablayout to display tabs  -->
    <android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
    <!-- View pager to swipe views -->
    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"/>
</LinearLayout>

و در  آخر کد java بخش Mainactivity که به شکل زیر می شود در زیر بخش main را گسترش داده و از بخش AppCompatActivity ابزار TabLayout را فراخوانی کرده ایم (علت این فراخوانی برای کلیک بروی هر یک از Tab هاست)

import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
//Implementing the interface OnTabSelectedListener to our MainActivity
//This interface would help in swiping views
public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener{
    //This is our tablayout
    private TabLayout tabLayout;
    //This is our viewPager
    private ViewPager viewPager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Adding toolbar to the activity
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //Initializing the tablayout
        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        //Adding the tabs using addTab() method
        tabLayout.addTab(tabLayout.newTab().setText("Tab1"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab3"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        //Initializing viewPager
        viewPager = (ViewPager) findViewById(R.id.pager);
        //Creating our pager adapter
        Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());
        //Adding adapter to pager
        viewPager.setAdapter(adapter);
        //Adding onTabSelectedListener to swipe views
        tabLayout.setOnTabSelectedListener(this);
    }
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        viewPager.setCurrentItem(tab.getPosition());
    }
    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
    }
    @Override
    public void onTabReselected(TabLayout.Tab tab) {
    }
}

آموزش به پایان رسید انشااالله در آینده با آموزش های بیشتری باز خواهیم گشت .
 

مطالعه بیشتر