Android tablayout+viewpager

Android tablayout+viewpager_第1张图片

1:依赖

implementation 'com.android.support:design:28.0.0'

2:布局




    

    

3:代码

public class Main2Activity extends AppCompatActivity {
    final Fragment[] fragments = {new BlankFragment(), new BlankFragment(), new BlankFragment()};
    final String[] titles = {"推荐", "热门", "附近"};

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

        vp.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return fragments[position];
            }

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

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return titles[position];
            }
        });
        tablayout.setupWithViewPager(vp);
        tablayout.setTabTextColors(getResources().getColor(R.color.txtblack),getResources().getColor(R.color.txtblue));//设置标题颜色
        tablayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.txtblue));//指示器颜色
        tablayout.getTabAt(0).select();//设置第一个为选中
    }

}

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