最终效果:
需求描述:
如上图,底部是数量不固定的选项卡,排列方式是剩余空间均分,点击切换tab时,被选中的tab会跟随动画,且展示对应tab的内容
需求拆分:
1. 关于动画,实现方式可以是加载gif文件;也可以采用lottie加载json文件。lottie的优势在于像素加载够清晰,如果lottie遇到加载问题,建议升级lottie库到最新版本。
2. 关于均匀分布,可以采用ConstraintLayout的chainStyle属性为spread实现;也可以使用LinearLayout在每个选项卡之间加入空的space控件,weight都是1,平分剩余空间。
3. 关于tab切换,实现方式有很多种,本文采用自定义view,定制化比较好,其他也可以采用Materail Design的BottomNavigationView或是TabLayout,但是定制需求比较受限,比如一些动画效果及字体样式等等
4.关于tab上方内容的显示,通常是通过切换不同的fragment实现tab切换加载不同的内容
需求实现:
引入需要的库:
implementation 'com.airbnb.android:lottie:3.4.0'
implementation 'com.github.bumptech.glide:glide:3.8.0'
1. 自定义tabItem项
在自定义View之前,先对加载View所需的数据结构进行定义,展示需要的元素有表明一个选项卡的唯一标识,动图资源,静图资源及tab名称,可以定义一个接口去实现它
public interface TabItem {
String getName();
@DrawableRes
int getStaticRes();
@DrawableRes
int getAnimateRes();
String getTabType();
}
自定义View的实现:
public class TabItemView extends FrameLayout {
private Context mContext;
private TextView mTabNameView;
private LottieAnimationView mTabLottieView;
private String mTabName;
private int mTabStaticRes;
private int mTabAnimateRes;
private boolean isSelected;
private int mSelectedTextColor;
private int mUnSelectedTextColor;
private int mTextSize;
private int mIconSize;
public TabItemView(@NonNull Context context) {
this(context, null);
}
public TabItemView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public TabItemView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public TabItemView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
mContext = context;
TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.TabItemView);
mTextSize = a.getDimensionPixelSize(R.styleable.TabItemView_textSize, 10);
mIconSize = a.getDimensionPixelSize(R.styleable.TabItemView_iconSize, 40);
mSelectedTextColor = a.getColor(R.styleable.TabItemView_selectedTextColor, getResources().getColor(R.color.tab_selected));
mUnSelectedTextColor = a.getColor(R.styleable.TabItemView_unSelectedTextColor, getResources().getColor(R.color.tab_unselected));
mTabStaticRes = a.getResourceId(R.styleable.TabItemView_mTabStaticRes, 0);
mTabAnimateRes = a.getResourceId(R.styleable.TabItemView_mTabAnimateRes, 0);
mTabName = a.getString(R.styleable.TabItemView_tabName);
a.recycle();
init();
}
private void init() {
View view = LayoutInflater.from(mContext).inflate(R.layout.bottom_tab_view_item, this, false);
mTabNameView = view.findViewById(R.id.tab_name);
mTabLottieView = view.findViewById(R.id.tab_animation_view);
addView(view);
}
private void setSelectedUI() {
if (mTabAnimateRes == 0) {
throw new NullPointerException("animation resource must be not empty");
} else {
mTabNameView.setTextColor(mSelectedTextColor);
mTabLottieView.setAnimation(mTabAnimateRes);
mTabLottieView.playAnimation();
}
}
private void setUnselectedUI() {
mTabNameView.setTextColor(mUnSelectedTextColor);
mTabLottieView.clearAnimation();
// 没有找到静态图,就选择加载gif图的第一帧,这里可以选择mipmap下的静图
Glide.with(mContext).load(mTabStaticRes).asBitmap().into(mTabLottieView);
}
public void updateUI() {
if (isSelected) {
setSelectedUI();
} else {
setUnselectedUI();
}
}
public TabItemView setIconSize(int iconSize) {
if (iconSize > 0) {
mIconSize = iconSize;
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mTabLottieView.getLayoutParams();
lp.width = mIconSize;
lp.height = mIconSize;
mTabLottieView.setLayoutParams(lp);
}
return this;
}
public TabItemView setStaticIcon(int staticRes) {
mTabStaticRes = staticRes;
return this;
}
public TabItemView setAnimateIcon(int animateRes) {
mTabAnimateRes = animateRes;
return this;
}
public TabItemView setTabName(String tabName) {
mTabName = tabName;
mTabNameView.setText(mTabName);
return this;
}
public TabItemView setTextColor(int selectColor, int unSelectColor) {
this.mSelectedTextColor = selectColor;
this.mUnSelectedTextColor = unSelectColor;
return this;
}
public TabItemView setTabSelected(boolean isSelected) {
this.isSelected = isSelected;
updateUI();
return this;
}
public TabItemView setTabTextSize(int textSize) {
this.mTextSize = textSize;
mTabNameView.setTextSize(mTextSize);
return this;
}
}
2. 对item项的加载进行封装
public class BottomTabNavigation extends LinearLayout implements View.OnClickListener {
public static final String TAB_NONE = "none";
public static final String TAB_HOME = "home";
public static final String TAB_CLOUD = "cloud";
public static final String TAB_EXCHANGE = "exchange";
public static final String TAB_USER_CENTER = "user_center";
private Context mContext;
private List<TabItem> tabList = new ArrayList<>();
private TabSelectedListener tabSelectedListener;
private String selectedTabType = TAB_NONE;
@StringDef({TAB_HOME, TAB_CLOUD, TAB_EXCHANGE, TAB_USER_CENTER, TAB_NONE})
@Retention(RetentionPolicy.SOURCE)
public @interface BottomTabType {
}
public BottomTabNavigation(@NonNull Context context) {
this(context, null);
}
public BottomTabNavigation(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BottomTabNavigation(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public BottomTabNavigation(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
mContext = context;
setOrientation(LinearLayout.HORIZONTAL);
}
public void setTabItems(List<TabItem> tabList) {
removeAllViews();
this.tabList = tabList;
if (null == tabList || tabList.size() == 0)
return;
addView(getSpaceView());
for (int i = 0; i < tabList.size(); i++) {
TabItem tab = tabList.get(i);
TabItemView tabItemView = new TabItemView(mContext)
.setTabName(tab.getName())
.setStaticIcon(tab.getStaticRes())
.setAnimateIcon(tab.getAnimateRes());
tabItemView.setOnClickListener(this);
tabItemView.setTag(tab.getTabType());
addView(tabItemView);
addView(getSpaceView());
}
if (selectedTabType.equals(TAB_NONE)) {
getChildAt(1).performClick();
}
}
private Space getSpaceView() {
Space space = new Space(mContext);
space.setLayoutParams(new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1));
return space;
}
@Override
public void onClick(View v) {
if (null == v.getTag())
return;
String tabType = (String) v.getTag();
if (tabType.equals(selectedTabType))
return;
if (null != tabSelectedListener) {
this.selectedTabType = tabType;
for (int i = 0; i < tabList.size(); i++) {
TabItem tab = tabList.get(i);
if (tabType.equals(tab.getTabType())) {
TabItemView tabView = (TabItemView) v;
tabView.setTabSelected(true);
tabSelectedListener.tabSelected(tabView);
} else {
TabItemView tabView = (TabItemView) getChildAt(i * 2 + 1);
tabSelectedListener.tabUnselected(tabView);
tabView.setTabSelected(false);
}
}
}
}
public void addOnTabSelectedListener(TabSelectedListener selectedListener){
this.tabSelectedListener = selectedListener;
}
public interface TabSelectedListener {
void tabSelected(TabItemView itemView);
void tabUnselected(TabItemView itemView);
}
}
3. 使用
public class MainActivity extends AppCompatActivity {
private HomeFragment homeFragment;
private UserCenterFragment userCenterFragment;
private ExchangeFragment exchangeFragment;
private CloudFragment cloudFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initFragment();
BottomTabNavigation navigation = findViewById(R.id.bottom_navigation);
navigation.addOnTabSelectedListener(new BottomTabNavigation.TabSelectedListener() {
@Override
public void tabSelected(TabItemView itemView) {
displayFragment((String) itemView.getTag());
}
@Override
public void tabUnselected(TabItemView itemView) {
}
});
navigation.setTabItems(getTabList());
}
private void initFragment() {
homeFragment = new HomeFragment();
cloudFragment = new CloudFragment();
exchangeFragment = new ExchangeFragment();
userCenterFragment = new UserCenterFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.add(R.id.fl_container, homeFragment)
.add(R.id.fl_container, exchangeFragment)
.add(R.id.fl_container, cloudFragment)
.add(R.id.fl_container, userCenterFragment)
.commitAllowingStateLoss();
}
private List<TabItem> getTabList() {
List<TabItem> tabs = new ArrayList<>();
tabs.add(new BottomTab("首页", BottomTabNavigation.TAB_HOME));
tabs.add(new BottomTab("云存储", BottomTabNavigation.TAB_CLOUD));
tabs.add(new BottomTab("交易", BottomTabNavigation.TAB_EXCHANGE));
tabs.add(new BottomTab("我的", BottomTabNavigation.TAB_USER_CENTER));
return tabs;
}
private void displayFragment(String selectTabType) {
switch (selectTabType) {
case BottomTabNavigation.TAB_HOME:
default:
getSupportFragmentManager().beginTransaction()
.show(homeFragment)
.hide(exchangeFragment)
.hide(cloudFragment)
.hide(userCenterFragment)
.commitAllowingStateLoss();
break;
case BottomTabNavigation.TAB_CLOUD:
getSupportFragmentManager().beginTransaction()
.show(cloudFragment)
.hide(exchangeFragment)
.hide(homeFragment)
.hide(userCenterFragment)
.commitAllowingStateLoss();
break;
case BottomTabNavigation.TAB_EXCHANGE:
getSupportFragmentManager().beginTransaction()
.show(exchangeFragment)
.hide(homeFragment)
.hide(cloudFragment)
.hide(userCenterFragment)
.commitAllowingStateLoss();
break;
case BottomTabNavigation.TAB_USER_CENTER:
getSupportFragmentManager().beginTransaction()
.show(userCenterFragment)
.hide(exchangeFragment)
.hide(cloudFragment)
.hide(homeFragment)
.commitAllowingStateLoss();
break;
}
}
}
其他问题:
1. 本文是基于参考https://blog.csdn.net/yiranhaiziqi/article/details/88965548文章实现的效果,对此表示感谢
2. 关于本文所用的动画资源来自于lottie提供的动画资源,具体地址是https://lottiefiles.com/user/475858,也可自行下载其他资源,可以下载gif,也可以下载json文件,感谢动画作者提供的资源;
3. 非选中状态时的静态图未找到对应的,demo采用只加载gif图第一帧的方式实现
4. 遇到lottie动画造成的崩溃【java.lang.IllegalStateException: Missing values for keyframe】
请将lottie动画库升级到3.0以上,具体参见https://www.freesion.com/article/1000623784/
github地址:
https://github.com/Jane205/BottomNavigation