Toolbar不通过ViewPager生成tab,自定义tab生成:
toolbar_tl_tab = findView(R.id.toolbar_tl_tab);
toolbar_tl_tab.setTabMode(TabLayout.MODE_SCROLLABLE);//TabLayout.MODE_FIXED 屏幕等分宽度模式,默认模式
String[] titles = {"常服药物", "常见药物"};
for (int i = 0; i < titles.length; i++) {
toolbar_tl_tab.addTab(toolbar_tl_tab.newTab().setText(titles[i]), i);
//设置tab选中及默认状态
toolbar_tl_tab.setTabTextColors(getResources().getColor(R.color.black), getResources().getColor(R.color.primary));
}
toolbar_tl_tab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
//选中是回调
@Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
Log.d("TAG", "0");
break;
case 1:
Log.d("TAG", "1");
break;
default:
break;
}
}
//从选中到不再选中时回调
@Override
public void onTabUnselected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
Log.d("TAG", "onTabUnselected 0");
break;
case 1:
Log.d("TAG", "onTabUnselected 1");
break;
default:
break;
}
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
Log.d("TAG", "onTabReselected");
}
});
xml
<android.support.design.widget.TabLayout
android:id="@+id/toolbar_tl_tab"
android:layout_width="0dp"
android:layout_height="@dimen/size40"
android:layout_gravity="bottom"
android:layout_weight="1"
app:layout_scrollFlags="scroll"
app:tabIndicatorColor="@color/primary"
app:tabSelectedTextColor="@color/primary" />