1.加载依赖
api "com.android.support:design:26.1.0"
2.布局
<android.support.design.widget.TabLayout android:id="@+id/timeline_tablayout" android:layout_width="match_parent" android:layout_height="wrap_content"/>
3.初始化和监听
private void initTab(){ TabLayout.Tab tab =mTabLayout.newTab(); tab.setText("默认"); tab.setTag(0); mTabLayout.addTab(tab); tab =mTabLayout.newTab(); tab.setText("价格"); tab.setTag(1); mTabLayout.addTab(tab); tab =mTabLayout.newTab(); tab.setTag(2); tab.setText("销量"); mTabLayout.addTab(tab); mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { Log.d(TAG, "onTabSelected: "+tab.getTag()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); }
4完成