1. 程式人生 > >Tablayout和Viewpager切換

Tablayout和Viewpager切換

依賴

    implementation 'com.flyco.tablayout:FlycoTabLayout_Lib:[email protected]'

    implementation 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <com.flyco.tablayout.SlidingTabLayout
        android:id="@+id/sil"
        android:layout_width="match_parent"
        android:layout_height="20dp"
        app:tl_divider_color="@color/colorAccent"
        app:tl_textUnselectColor="@color/colorPrimary"
        app:tl_indicator_width_equal_title="true"
        app:tl_divider_width="1dp"
        app:tl_tab_space_equal="true"
        app:tl_indicator_color="#d91212"
        app:tl_textSelectColor="@color/colorPrimary"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/vp_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>


</LinearLayout>

主頁面

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;

import com.flyco.tablayout.SlidingTabLayout;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.vp_main)
    ViewPager vpMain;
    @BindView(R.id.sil)
    SlidingTabLayout sil;
    private ArrayList<Fragment> fragments;
    private String[] a = new String[]{"未支付賬單", "支付中賬單", "歷史賬單"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        fragments = new ArrayList<>();
        fragments.add(new OneFragment());
        fragments.add(new TwoFragment());
        fragments.add(new ThreeFragment());
          sil.setViewPager(vpMain,a,this,fragments);
    }
}