实现主页面多个标签页切换
在这里实现了4个标签页的切换,比较简单且稳定的实现方式,容易理解,先上效果图:
页面很简单,连按钮都是一样的,手太懒了,要不是需要两个图片,我就用ic_launch了
下面4个是切换按钮,几个都一样,根据需求随意删加即可,上面的大白页就是我们的Fragment了,需要的话就在上面弄布局,自定义的BottomBar很好理解,基本常识,废话少说上代码(用的话复制粘贴简单修改就OK,我也会上传源码):
1.MainActivity(用来放置BottomBar控件和碎片),最下面那个方法是用来检测按两次返回键退出应用的,不需要的直接删了就行:
package com.thecanteensoftware.activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.widget.LinearLayout; import com.thecanteensoftware.R; import com.thecanteensoftware.frg.MainFragment; import com.thecanteensoftware.frg.MineFragment; import com.thecanteensoftware.frg.RecommendFragment; import com.thecanteensoftware.frg.ShoppingCartFragment; import com.thecanteensoftware.util.UtilToast; import com.thecanteensoftware.view.BottomBar; import com.thecanteensoftware.view.BottomBarTab; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends AppCompatActivity { /** * 4个页面碎片 */ private MainFragment mainFragment; private MineFragment mineFragment; private RecommendFragment recommendFragment; private ShoppingCartFragment shoppingCartFragment; private FragmentManager fragmentManager; private LinearLayout mainContainer; private BottomBar bottomBar; private Fragment fragment; int clickBackCount = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); barListener(); } public void initView(){ mainContainer = (LinearLayout) findViewById(R.id.main_container); bottomBar = (BottomBar) findViewById(R.id.bottomBar); /** * 第二个参数是选中后显示的图片,第三个是未选中时的图片,第四个是页面名字 */ BottomBarTab bottomBarTab0 = new BottomBarTab(this, R.mipmap.category_, R.mipmap.category, "菜单"); BottomBarTab bottomBarTab1 = new BottomBarTab(this, R.mipmap.category_, R.mipmap.category, "推荐"); BottomBarTab bottomBarTab2 = new BottomBarTab(this, R.mipmap.category_, R.mipmap.category, "购物车"); BottomBarTab bottomBarTab3 = new BottomBarTab(this, R.mipmap.category_, R.mipmap.category, "我的"); bottomBar.addItem(bottomBarTab0); bottomBar.addItem(bottomBarTab1); bottomBar.addItem(bottomBarTab2); bottomBar.addItem(bottomBarTab3); fragmentManager = getSupportFragmentManager(); } /** * 填充按钮上方Framgment布局 */ public void barListener(){ bottomBar.setListener(new BottomBar.OnTabItemClickListener() { @Override public void onClick(int position) { switch (position) { case 0: if (mainFragment == null) { mainFragment = new MainFragment(); getSupportFragmentManager().beginTransaction() .add(R.id .main_container, mainFragment) .commit(); } else { if (fragment == null) { fragmentManager.beginTransaction(