日了狗的TabLayout+viewPager实现

 
  



    
    

    

    



import android.content.Context;
import android.os.Bundle;
import android.provider.SyncStateContract;
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.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        MyAdapter myAdapter = new MyAdapter();
        viewPager.setAdapter(myAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        tabLayout.setupWithViewPager(viewPager);
        //tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_bianji));
        //tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_xuanze));


        tabLayout.getTabAt(0).setIcon(R.drawable.ic_bianji);
        tabLayout.getTabAt(1).setIcon(R.drawable.ic_xuanze);

    }
    /**
     * 自定义类实现PagerAdapter,填充显示数据
     */
    class MyAdapter extends PagerAdapter {
        // 显示多少个页面
        @Override
        public int getCount() {
            return 2;
        }

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

        // 初始化显示的条目对象
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // return super.instantiateItem(container, position);
            // 准备显示的数据,一个简单的TextView
            TextView tv = new TextView(MainActivity.this);
            tv.setGravity(Gravity.CENTER);
            tv.setTextSize(20);
            int positions = position+1;
            tv.setText("这是第" + positions + "页");

            // 添加到ViewPager容器
            container.addView(tv);

            // 返回填充的View对象
            return tv;
        }

        // 销毁条目对象
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // super.destroyItem(container, position, object);
            container.removeView((View) object);
        }
    }
}



你可能感兴趣的:(日了狗的TabLayout+viewPager实现)