Android实现Tablayout滑动

Activity.java

package com.example.xiaoqu.name;

import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.util.ArrayList;
import java.util.List;

public class TabActinity extends AppCompatActivity {


    private ViewPager viewpager;
    private List list = new ArrayList<>();
    private TabLayout tablayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab_actinity);
        tablayout =  (TabLayout)findViewById(R.id.tablayout);
         viewpager =   (ViewPager)findViewById(R.id.viewpager);

         MyAdapter myAdapter = new MyAdapter(getSupportFragmentManager());
         viewpager.setAdapter(myAdapter);
         tablayout.setupWithViewPager(viewpager);
        tablayout.setTabMode(TabLayout.MODE_SCROLLABLE);


    }
    // 内部适配器
     class  MyAdapter extends FragmentPagerAdapter{

          String title[] = {"自定义1","自定义1"};
         public MyAdapter(FragmentManager fm) {
             super(fm);
             list.add(new Afragment());
             list.add(new Bfragment());
         }

         @Override
         public Fragment getItem(int i) {
             return list.get(i);
         }

         @Override
         public int getCount() {
             return list.size();
         }

         @Nullable
         @Override
         public CharSequence getPageTitle(int position) {
             return title[position];
         }
     }
}

activity.xml




     
     

    
    


记得加入依赖

你可能感兴趣的:(Android实现Tablayout滑动)