Android,实现Fragment切换

话不多说先上效果演示

演示

还包括了NavigationView(导航抽屉)的效果,不会的可以先看
NavigationView(导航抽屉)

在Mainactivity中进行设置

/*设置mainactivity的布局文件*/
@Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }
/*初始化各种Fragment类*/
    private void initFragment() {
        homeFragment = new HomeFragment();
        managerFragment = ManagerFragment.newInstance();
        favorityFragment = FavorityFragment.newInstance();
        settingFragment = SettingFragment.newInstance();
        borrowFragment = BorrowFragment.newInstance();
        fragments = new Fragment[]{
                homeFragment,
                managerFragment,
                favorityFragment,
                settingFragment,
                borrowFragment
        };
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.container, homeFragment)
                .show(homeFragment).commit();
    }
    
    /*初始化NavigationView*/
    private void initNavigationView() {
        mNavigationView.setNavigationItemSelectedListener(this);
        View headerView = mNavigationView.getHeaderView(0);
        CircleImageView mUserAvatarView = (CircleImageView) headerView.findViewById(R.id.user_avatar_view);
        TextView mUserName = (TextView) headerView.findViewById(R.id.user_name);
        TextView mUserLevel = (TextView) headerView.findViewById(R.id.user_level);
        String name = getSharedPreferences("user", MODE_PRIVATE).getString("username", "听雨喧");
        userLevel = DbUtil.getUserLevel(this, name);
        mUserLevel.setText("LV"+ userLevel);
        //设置名字
        mUserName.setText(name);

    }

    /*点击NavigationView*/
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.item_exit:
                //切换帐号
                getSharedPreferences("user", MODE_PRIVATE).edit().putString("username","").commit();
                startActivity(new Intent(this,LoginActivity.class));
                finish();
                break;
            //主页
            case R.id.item_home:
                toggleDrawer();
                changeFragmentIndex(item, 0);
                boolean update = getSharedPreferences("book", MODE_PRIVATE).getBoolean("update", false);
                //System.out.println("-0-----------------dianjile--item_home:"+update);
                if(update){
                    homeFragment.reFreshData();
                }
                break;
            //管理界面
            case R.id.item_manager:
                toggleDrawer();
                if(userLevel<2){
                    ToastUtil.showLong(this,"抱歉,只有管理员才能进入");
                }else {
                    changeFragmentIndex(item, 1);
                }
                break;
            //收藏图书界面
            case R.id.item_favourite:
                toggleDrawer();
                changeFragmentIndex(item, 2);
                break;

            //设置界面
            case R.id.item_settings:
                toggleDrawer();
                changeFragmentIndex(item,3);
                break;

            case R.id.item_history:
                toggleDrawer();
                changeFragmentIndex(item, 4);
                break;

        }
        return false;
    }

    private void showManagerFragment() {

    }

    /**
     * DrawerLayout侧滑菜单开关
     */
    public void toggleDrawer() {
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        } else {
            mDrawerLayout.openDrawer(GravityCompat.START);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mDrawerLayout.isDrawerOpen(mDrawerLayout.getChildAt(1))) {
                mDrawerLayout.closeDrawers();
            } else {
                exitApp();
            }
        }
        return true;
    }
    /**
     * 双击退出App
     */
    private long exitTime;
    private void exitApp() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            ToastUtil.showShort(this,"再按一次退出");
            exitTime = System.currentTimeMillis();
        } else {
//            PreferenceUtil.remove(ConstantUtil.SWITCH_MODE_KEY);
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        exitApp();
        super.onBackPressed();

    }

    private int currentTabIndex;
    private int index;

    /**
     * Fragment切换
     */
    private void switchFragment() {
        FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
        trx.hide(fragments[currentTabIndex]);
        if (!fragments[index].isAdded()) {
            trx.add(R.id.container, fragments[index]);
        }
        trx.show(fragments[index]).commit();
        currentTabIndex = index;
    }

    /**
     * 切换Fragment的下标
     */
    private void changeFragmentIndex(MenuItem item, int currentIndex) {
        index = currentIndex;
        switchFragment();
        item.setChecked(true);
    }

自定义的BaseFragment(创建的Fragment类都继承自BaseFragment),没什么具体的干货,可以不用仔细看

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import tingyuxuan.hosition.zxyoyo.com.tingyuxuan.utils.LogUtil;

/**
 * ---------------------------------------------
 * Created by small-star-star on 2017/10/18.
 * tel:[email protected]
 * 纸上得来终觉浅
 * fragment基础类
 * ---------------------------------------------
 */

public abstract class BaseFragment extends Fragment {
    protected View parentView;
    //初始化完成
    protected boolean isPrepared;
    //fragment可见
    protected boolean isVisiable;
    private Unbinder bind;

    public abstract
    @LayoutRes
     int getLayoutResId();

    private FragmentActivity activity;
    private Context context;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        activity = getSupportActivity();
        parentView = inflater.inflate(getLayoutResId(),container,false);
        LogUtil.e("fragmentlife","onCreateView");
        return parentView;
    }


    public FragmentActivity getSupportActivity(){
        return super.getActivity();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        bind = ButterKnife.bind(this,view);
        finishCreateView(savedInstanceState);
        LogUtil.e("fragmentlife","onViewCreated");
    }

    /**
     * 初始化view
     * @param state
     */
    public abstract void finishCreateView(Bundle state);


    @Override
    public void onResume() {
        super.onResume();
        LogUtil.e("fragmentlife","onResume");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        bind.unbind();
        LogUtil.e("fragmentlife","onDestroy");
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
        LogUtil.e("fragmentlife","onAttach");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        this.context = null;
        LogUtil.e("fragmentlife","onDetach");
    }

    /**
     * 数据懒加载
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        LogUtil.e("fragmentlife","setUserVisibleHint-"+isVisibleToUser);
        if(getUserVisibleHint()){
            isVisiable = true;
            onVisiable();
        }else {
            isVisiable  = false;
            onInvisiable();
        }
    }

    /**
     * fragment不可见
     */
    protected  void onInvisiable(){

    }

    /**
     * fragment 可见
     */
    protected  void onVisiable(){
        loadData();
    }

    /**
     * 加载数据
     */
    protected  void loadData(){

    }

    /**
     * 初始化recyclerView
     */
    protected void initRecyclerView() {
    }

    /**
     * 初始化refreshLayout
     */
    protected void initRefreshLayout() {
    }

    /**
     * 设置数据显示
     */
    protected void finishTask() {
    }


}

MainActivity的布局

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">
    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="320dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@color/navigation_background_light"
        android:overScrollMode="never"
        app:headerLayout="@layout/layout_navigation_header"
        app:menu="@menu/navigation_main" />

</android.support.v4.widget.DrawerLayout>

复制上去肯定会报错,因为缺少了navigation_main.xml和layout_navigation_header.xml
在res下创建menu文件夹,然后在menu文件下创建navigation_main.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/item_home"
            android:checked="true"
            android:icon="@drawable/ic_home_black_24dp"
            android:title="@string/item_home" />


    </group>


    <group
        android:id="@+id/group_user"
        android:checkableBehavior="single">

        <item
            android:id="@+id/item_favourite"
            android:icon="@drawable/ic_star_black_24dp"
            android:title="@string/item_favourite" />

        <item
            android:id="@+id/item_history"
            android:icon="@drawable/ic_history_black_24dp"
            android:title="@string/item_history" />


    </group>


    <group android:checkableBehavior="single">

        <item
        android:id="@+id/item_settings"
        android:icon="@drawable/ic_settings_black_24dp"
        android:title="@string/item_settings" />
        <item
            android:id="@+id/item_manager"
            android:icon="@drawable/ic_manager"
            android:title="@string/item_manager" />
        <item
            android:id="@+id/item_exit"
            android:icon="@drawable/ic_exit_to_app_black_24dp"
            android:title="@string/item_exit" />

    </group>

</menu>

layout_navigation_header布局文件如下:
在这里插入图片描述

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:id="@+id/header_container"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:clickable="true">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimary">

        <ImageView
            android:id="@+id/background_image_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center|end|bottom"
            android:clickable="true"
            android:src="@drawable/home_menu_bg_click"
            android:tint="@color/nav_head_image_background" />
    </FrameLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:paddingTop="@dimen/activity_vertical_margin">

        <tingyuxuan.hosition.zxyoyo.com.tingyuxuan.view.design.CircleImageView
            android:id="@+id/user_avatar_view"
            android:layout_width="74dp"
            android:layout_height="74dp"
            android:layout_gravity="start|top"
            android:layout_marginEnd="16dp"
            android:layout_marginStart="@dimen/activity_vertical_margin"
            android:layout_marginTop="20dp"
            android:src="@drawable/ico_user_default"
            app:border_color="@android:color/white"
            app:border_width="1dp" />


        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_marginEnd="20dp"
            android:layout_marginTop="20dp"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/iv_head_noftiy"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_navigation_header_notification" />


        </LinearLayout>


        <LinearLayout
            android:id="@+id/subtitle_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/user_avatar_view"
            android:layout_gravity="bottom"
            android:layout_marginStart="10dp"
            android:background="?attr/selectableItemBackground"
            android:orientation="vertical"
            android:paddingTop="5dp">


            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:orientation="horizontal"
                android:padding="5dp">

                <TextView
                    android:id="@+id/user_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/app_name"
                    android:textColor="@color/white"
                    android:textSize="16sp" />

                <TextView
                    android:id="@+id/user_level"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="3dp"
                    android:background="@drawable/white_border"
                    android:text="LV1"
                    android:gravity="center"
                    android:textColor="@color/white"
                    android:textSize="10sp" />

            </LinearLayout>


            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="3dp"
                android:background="@drawable/round_wihte_bg"
                android:padding="3dp"
                android:text="@string/app_name"
                android:textColor="@color/nav_head_roung_text_background"
                android:textSize="10sp" />

            <TextView
                android:text="@string/header_introduce"
                android:id="@+id/user_other_info"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="3dp"
                android:textColor="@color/white"
                android:textSize="14sp" />
        </LinearLayout>

    </RelativeLayout>


</FrameLayout>
发布了34 篇原创文章 · 获赞 2 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_38420342/article/details/105483283