问题描述
问题1 如何实现一个Activity多个Fragment
问题2 底部导航栏fragment切换时会反复加载网络数据,最终造成网络阻塞甚至崩溃
底部导航栏切换时如果使用remove和add方法,这样每次切换都会导致创建多个Fragment实例,所以造成网络阻塞甚至程序崩溃。这里采用hide和show方法来切换fragment
问题3 去掉BottomNavigationMenuView的默认动画效果
为了方便布局采用了BottomNavigationMenuView进行底部导航栏布局,但当底部按钮数量较多时,会有个自带动画效果,这显然不是我们想要的,可以通过反射去掉这个效果。
下面说解决方案
代码实现
编写Fragment,这里创了5个简易的Fragment,代码都是类似的
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import example.com.myapplication.R;
public class FiveFragment extends Fragment {
public FiveFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_five, container, false);
}
}
对Fragment布局,这里只是简单地加了个背景
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/md_light_green_A700"/>
</LinearLayout>
添加design包,这里版本号根据实际情况自行更改
compile 'com.android.support:design:25.3.1'
activity_main.xml布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"/>
<android.support.design.widget.BottomNavigationView
android:id="@+id/bottomNav"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="?android:attr/windowBackground"
app:itemBackground="@null"
app:itemIconTint="@drawable/bottom_navigation_selector"
app:itemTextColor="@drawable/bottom_navigation_selector"
app:menu="@menu/tab" />
</LinearLayout>
添加tab.xml 用于按钮文字及图片配置
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/navigation_home"
android:icon="@drawable/home"
android:title="首页" />
<item
android:id="@+id/navigation_two"
android:icon="@drawable/home"
android:title="分类"
/>
<item
android:id="@+id/navigation_three"
android:icon="@drawable/home"
android:title="圈子"
/>
<item
android:id="@+id/navigation_four"
android:icon="@drawable/home"
android:title="发现" />
<item