您的位置:

Android Fragment切换详解

一、Fragment简介

在Android应用程序中,Fragment是一种可重用的组件,用于构建灵活的用户界面。与Activity一样,Fragment具有自己的用户界面,不过它显示在Activity的UI内。在同一个Activity中,可以同时使用多个Fragment,并且可以动态添加、移除、替换。Fragment的生命周期也是独立的,因此它们可以根据需要进行管理。

二、Fragment切换方式

1、通过点击按钮切换

在Activity中添加一个按钮,点击按钮时切换Fragment。关键代码如下:

public class MainActivity extends AppCompatActivity {
    private Button button1, button2;
    private Fragment fragment1, fragment2;
    private FragmentManager fragmentManager;
    private FragmentTransaction transaction;
    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fragmentManager = getSupportFragmentManager();
        transaction = fragmentManager.beginTransaction();
        
        //初始化Fragment1
        fragment1 = new Fragment1();
        transaction.replace(R.id.fragment_container, fragment1);
        transaction.commit();

        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);

        //点击Button1
        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                transaction = fragmentManager.beginTransaction();
                fragment1 = new Fragment1();
                transaction.replace(R.id.fragment_container, fragment1);
                transaction.commit();
            }
        });

        //点击Button2
        button2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                transaction = fragmentManager.beginTransaction();
                fragment2 = new Fragment2();
                transaction.replace(R.id.fragment_container, fragment2);
                transaction.commit();
            }
        });
    }
}

2、通过ViewPager切换

通过ViewPager实现Fragment之间的滑动切换,需要创建一个包含多个Fragment的FragmentPagerAdapter。关键代码如下:

public class MainActivity extends AppCompatActivity {
    private PagerAdapter pagerAdapter;
    private ViewPager viewPager;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager = (ViewPager) findViewById(R.id.view_pager);
        pagerAdapter = new PagerAdapter(getSupportFragmentManager());

        pagerAdapter.addFragment(new Fragment1(), "Fragment1");
        pagerAdapter.addFragment(new Fragment2(), "Fragment2");
        pagerAdapter.addFragment(new Fragment3(), "Fragment3");

        viewPager.setAdapter(pagerAdapter);
        viewPager.setCurrentItem(0);
    }

    static class PagerAdapter extends FragmentPagerAdapter {
        private final List fragmentList = new ArrayList<>();
        private final List
    fragmentTitleList = new ArrayList<>();

        public PagerAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
        }

        public void addFragment(Fragment fragment, String title) {
            fragmentList.add(fragment);
            fragmentTitleList.add(title);
        }

        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        public int getCount() {
            return fragmentList.size();
        }

        public CharSequence getPageTitle(int position) {
            return fragmentTitleList.get(position);
        }
    }
}

   
  

3、通过BottomNavigationView切换

在布局文件中添加BottomNavigationView,通过Java代码监听点击事件,实现Fragment之间的切换。关键代码如下:

public class MainActivity extends AppCompatActivity {
    private FragmentManager fragmentManager;
    private Fragment1 fragment1;
    private Fragment2 fragment2;
    private Fragment3 fragment3;
    private BottomNavigationView bottomNavigationView;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fragmentManager = getSupportFragmentManager();
        fragment1 = new Fragment1();
        fragment2 = new Fragment2();
        fragment3 = new Fragment3();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.fragment_container, fragment1, "fragment1");
        transaction.add(R.id.fragment_container, fragment2, "fragment2");
        transaction.add(R.id.fragment_container, fragment3, "fragment3");
        transaction.hide(fragment2);
        transaction.hide(fragment3);
        transaction.commit();

        bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                FragmentTransaction transaction = fragmentManager.beginTransaction();
                switch (menuItem.getItemId()) {
                    case R.id.navigation_home:
                        transaction.hide(fragment2);
                        transaction.hide(fragment3);
                        transaction.show(fragment1);
                        transaction.commit();
                        return true;
                    case R.id.navigation_dashboard:
                        transaction.hide(fragment1);
                        transaction.hide(fragment3);
                        transaction.show(fragment2);
                        transaction.commit();
                        return true;
                    case R.id.navigation_notifications:
                        transaction.hide(fragment1);
                        transaction.hide(fragment2);
                        transaction.show(fragment3);
                        transaction.commit();
                        return true;
                }
                return false;
            }
        });
    }
}

三、Fragment结合使用

在Android应用中,我们经常使用Fragment结合使用。例如,如果我们要实现一个应用,要求在不同的Fragment之间传递数据,那么应该怎么做呢?

1、向Fragment传递数据

在Activity中调用Fragment的构造函数,向Fragment传递数据。关键代码如下:

public class MainActivity extends AppCompatActivity {
    private String data = "Hello, Fragment!";
    private Fragment fragment;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fragment = new Fragment1(data);
    }
}

public class Fragment1 extends Fragment {
    private String data;
    private TextView textView;

    public Fragment1(String data) {
        this.data = data;
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment1, container, false);
        textView = (TextView) view.findViewById(R.id.textView);
        textView.setText(data);
        return view;
    }
}

2、从Fragment获取数据

通过在Fragment中定义接口,让Activity来实现这个接口,从而获取Fragment的数据。关键代码如下:

public class MainActivity extends AppCompatActivity implements Fragment1.OnFragmentInteractionListener {
    private Fragment1 fragment1;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fragment1 = new Fragment1();
        getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment1).commit();
    }

    public void onFragmentInteraction(Uri uri) {
        //获取Fragment中的数据
        String data = fragment1.getData();
    }
}

public class Fragment1 extends Fragment {
    private OnFragmentInteractionListener mListener;

    public Fragment1() {
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment1, container, false);
        return view;
    }

    public String getData() {
        //获取数据并返回
        return "Hello";
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }
}

四、总结

本文从Fragment的基本概念开始介绍,逐步展开到Fragment切换的三种方式以及Fragment结合使用的示例。希望本文能够对你的学习有所帮助。

Android Fragment切换详解

2023-05-21
Fragment切换详解

2023-05-20
Android横竖屏切换的生命周期管理

Android设备支持横向和纵向两种屏幕方向,应用程序在不同的方向下可能会有不同的布局和展示效果。然而,当用户旋转设备屏幕时,应用程序并不一定会正确地重新加载并展示内容,这可能会导致崩溃或不完整的界面

2023-12-08
增强用户体验:Android Fragment切换实现流畅界

2023-05-14
Android Studio Fragment使用示例

2023-05-14
Android Fragment实现页面模块化

2023-05-14
Android Fragment应用——如何实现页面模块化

一、什么是Fragment Fragment是Android系统中的一种组件,可以看做是Activity的子页面,一般是被一个Activity承载着,是Activity的可重用的组成部分。通过将界面模

2023-12-08
掌握Android Fragment的生命周期

2023-05-14
印象笔记记录java学习(Java成长笔记)

2022-11-12
Fragment嵌套Fragment

2023-05-20
Fragment生命周期详解

2023-05-18
阿里云笔记的功能与使用详解

2023-05-21
java方法整理笔记(java总结)

2022-11-08
AndroidX:简化Android项目依赖管理

2023-05-14
Android登录界面跳转:实现页面之间的无缝衔接

2023-05-14
java笔记,尚硅谷java笔记

2022-12-01
java客户端学习笔记(java开发笔记)

2022-11-14
发篇java复习笔记(java课程笔记)

2022-11-09
如何在Android Fragment中实现数据传递

一、使用Bundle传递数据 在Fragment中可以通过创建Bundle对象将数据传递给另外一个Fragment或者Activity。 // 创建一个Bundle对象,并将数据添加到Bundle中

2023-12-08
python基础学习整理笔记,Python课堂笔记

2022-11-21