(如果想要快速的办法,建议直接在建module的时候选择Bottom Navigation Activity,用Android的默认模板)
先看效果:
Bottom navigation bar
从上面的视频可以看到我需要创建4个Fragment才能实现这种效果。
我在包里创建了一个Fragment文件夹专门来放fragment文件,下面就是我创建的四个Fragment文件的地址以及四个Fragment文件:
FrontFragment(首页):
public class FrontFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.front_fragment, null);
return view;
}
}
下面是Fragment文件对应的布局文件
front_fragment(首页):
上面的Fragment以及它们对应的布局文件都是一样的,为的就是展示页面切换的效果。下面才是重头戏。
布局文件activity_main.xml:
在这个布局文件中父容器用了相对布局管理器--RelativeLayout,具体的布局方式如下:
frameLayout是页面切换的部分,我需要在页面布局的时候给它个位置:
下面的LinearLayout是一个水平的线性布局管理器(也就是底部导航栏),在这里我需要四个ImageButton来对应四个Fragment,但是我的Image上没有文字说明,所以我还要添加一个TextView来对按钮进行文字说明,我的每个ImageButton外面还得有一个相对布局管理器来把ImageButton和TextView包起来。具体看下图:
具体代码如下:
页面布局部分讲完就到activity部分了。
首先就是初始化,声明变量:
FragmentManager fragmentManager; FragmentTransaction fragmentTransaction; Fragment f = null;
获取按钮对象:
ImageButton imageButton1 = findViewById(R.id.image1); ImageButton imageButton2 = findViewById(R.id.image2); ImageButton imageButton3 = findViewById(R.id.image3); ImageButton imageButton4 = findViewById(R.id.image4);
点击事件监听:
imageButton1.setonClickListener(listener); imageButton2.setonClickListener(listener); imageButton3.setonClickListener(listener); imageButton4.setonClickListener(listener);
默认第一页为 FrontFragment:
fragmentManager = getSupportFragmentManager(); fragmentTransaction = fragmentManager.beginTransaction(); f = new FrontFragment(); fragmentTransaction.add(R.id.fragment, f); fragmentTransaction.commit();
接口重写onClickListener方法,判断点击事件,进行页面切换:
View.onClickListener listener = new View.onClickListener() {
@Override
public void onClick(View view) {
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
switch (view.getId()) {
case R.id.image1:
f = new FrontFragment();
break;
case R.id.image2:
f = new LightFragment();
break;
case R.id.image3:
f = new DeviceFragment();
break;
case R.id.image4:
f = new MimeFragment();
break;
default:
break;
}
fragmentTransaction.replace(R.id.fragment, f);
fragmentTransaction.commit();
}
};



