当然的应用太多Tab+Fragment.
实现方式多种多样:
TabLayout+Fragment
常规布局+Frament
FragmentTabHost+Fragment
然后遇到特殊的Tab,比如一个Tab含有右上角有一个数字提醒或者Label,可能需要自行布局才能满足需求。为了方便以后的复用,使用自定义的Tab来满足需求。
TabInfo:
public class TabInfo {
private int count;//Tab的个数 必选
private int currentTab;//默认选中的tab 必选
private String[] tabText;//文字必选
private int normalResId;//可选
private int selectResId;//可选
private int normalTextColor;//可选
private int selectTextColor;//可选
private int normalTextSizeSp;//可选
private int selectTextSizeSp;//可选
}
CustomTabLayout:
继承LinearLayout,外部传入布局,内部控制imageview,textview的显示状态与点击回调
public void addTab(List<TabInfo> tabInfos, int layout) {
this.tabInfos = tabInfos;
tabLayout = layout;
tabLayout = getItemLayout(tabLayout);
if (tabLayout <= 0) {
return;
}
for (int i = 0; i < tabInfos.size(); i++) {
View view = LayoutInflater.from(getContext()).inflate(tabLayout, null);
RelativeLayout itemLayout = (RelativeLayout) view.findViewById(R.id.custom_tablayout_item);
itemLayout.setGravity(Gravity.CENTER);
LayoutParams layoutParams = new LayoutParams(0, ViewGroup.LayoutParams.FILL_PARENT, 1.0f);
itemLayout.setLayoutParams(layoutParams);
TextView textView = (TextView) view.findViewById(R.id.custom_tablayout_text);
ImageView imageView = (ImageView) view.findViewById(R.id.custom_tablayout_image);
imageViews.add(imageView);
textViews.add(textView);
//设置文字
textView.setText(tabInfos.get(i).getTabText()[i]);
if (position >= tabInfos.size() || position < 0) {
position = 0;
} else {
position = tabInfos.get(i).getCurrentTab();
}
//选中的图片和颜色
if (i == tabInfos.get(i).getCurrentTab()) {
setTextSizeofSp(textView, tabInfos.get(i).getSelectTextSizeSp());
textView.setTextColor(tabInfos.get(i).getSelectTextColor());
imageView.setImageResource(tabInfos.get(i).getSelectResId());
} else {
setTextSizeofSp(textView, tabInfos.get(i).getNormalTextSizeSp());
textView.setTextColor(tabInfos.get(i).getNormalTextColor());
imageView.setImageResource(tabInfos.get(i).getNormalResId());
}
addView(view);
final int finalI = i;
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
setSelectTab(finalI);
onTabOnclickListener.onTabClick(finalI, imageViews.get(finalI), textViews.get(finalI));
}
});
}
}
外部使用:
customTabLayout = (CustomTabLayout) findViewById(R.id.custom_tablayout);
//strs:文字描述 5:有5个Tab 0:默认选中的是第一个
TabInfo.TabInfoBuilder tabInfoBuilder = new TabInfo.TabInfoBuilder(strs,count, 0);
List<TabInfo> tabInfos = new ArrayList<>();
for (int i = 0; i < count; i++) {
TabInfo tabInfo = tabInfoBuilder
.setNormalResId(normalResId[i])
.setSelectResId(selectResId[i])
.setNormalTextSizeSp(12)
.setSelectTextSizeSp(12)
.setNormalTextColor(getResources().getColor(R.color.colorAccent))
.setSelectTextColor(getResources().getColor(R.color.colorPrimaryDark))
.build();
tabInfos.add(tabInfo);
}
customTabLayout.addTab(tabInfos,R.layout.tablayout_item);//代码设置布局
// customTabLayout.addTab(tabInfos); xml设置布局调用方式