关闭

TabLayout使用

101人阅读 评论(0) 收藏 举报
public class MainActivity extends AppCompatActivity {
   private TabLayout    mTabLayout;
   private ViewPager    mViewPager;
   private PagerAdapter viewPagerAdapter;
   private String[] mTitle = new String[8];
   private String[] mData  = new String[8];

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      mTabLayout = (TabLayout) findViewById(R.id.tl);
      mViewPager = (ViewPager) findViewById(R.id.viewpager);

      for (int i = 0; i < 8; i++) {
         mTitle[i] = "title" + i;
         mData[i] = "data" + i;
      }

      initPagerAdapter();//
//    initFragPagerAdapter();
      test();
   }



   private void initPagerAdapter() {
      viewPagerAdapter = new PagerAdapter() {
         @Override
         public CharSequence getPageTitle(int position) {
            return mTitle[position];
         }

         @Override
         public int getCount() {
            return mData.length;
         }

         @Override
         public Object instantiateItem(ViewGroup container, int position) {
            TextView tv = new TextView(MainActivity.this);
            tv.setTextSize(30.f);
            tv.setText(mData[position]);
            ((ViewPager) container).addView(tv);
            return tv;
         }

         @Override
         public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView((View) object);
         }

         @Override
         public boolean isViewFromObject(View view, Object object) {
            return view == object;
         }
      };

   }




   private void test() {
      mTabLayout.setTabsFromPagerAdapter(viewPagerAdapter);
      mViewPager.setAdapter(viewPagerAdapter);//
      mTabLayout.setupWithViewPager(mViewPager);//设置关联的ViewPager
      mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);//设置TaBlayout的滑动模式
   }



   private void initFragPagerAdapter() {
      ArrayList<Fragment> fragList = new ArrayList<Fragment>();//4MB
      fragList.add(new Frag());
      fragList.add(new Frag());
      fragList.add(new Frag());
      viewPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(),fragList,MainActivity.this);
   }


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2521次
    • 积分:151
    • 等级:
    • 排名:千里之外
    • 原创:13篇
    • 转载:4篇
    • 译文:0篇
    • 评论:0条