An_Tablayout+viewpager

package com.example.day12tablayout;

import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import org.w3c.dom.Text;

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

public class MainActivity extends AppCompatActivity {

    TabLayout tab;
    ViewPager vp;

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

        tab = (TabLayout) findViewById(R.id.tab);
        vp = (ViewPager) findViewById(R.id.vp);
        initData();
        MyAdapter myAdapter = new MyAdapter();
        vp.setAdapter(myAdapter);

//        for (int i = 0; i < 12; i++) {
//            tab.addTab(tab.newTab().setText("标题" + i));
//        }
        //设置可以滑动
        tab.setTabMode(TabLayout.MODE_SCROLLABLE);
        //当tabLayout和ViewPager进行绑定后   标题会消失
        //在PagerAdapter中要重写一个  getPageTitle()
        tab.setupWithViewPager(vp);
    }

    private void initData() {
        listStr = new ArrayList();
        listTv = new ArrayList();

        for (int i = 0; i < 10; i++) {
            String str = "条目" + i;
            listStr.add(str);
            TextView tv = new TextView(this);
            tv.setText(str);
            listTv.add(tv);
        }
    }

    class MyAdapter extends PagerAdapter{
        @Override
        public int getCount() {
            return listTv.size();
        }

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

        //ctrl + o
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(listTv.get(position));
            return listTv.get(position);
        }

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

        //在PagerAdapter和FragmentPagerAdapter中都有该方法
        @Override
        public CharSequence getPageTitle(int position) {
            return listStr.get(position);
        }
    }
}

你可能感兴趣的:(An_Tablayout+viewpager)