Android开发中嵌套fragment的实现

来源:互联网 发布:联合国维和行动 知乎 编辑:程序博客网 时间:2024/06/03 12:28

本次采用fragment+viewpager+adapter来实现fragment的嵌套


规划

本次嵌套,实现外面4个fragment可以滑动,也可以通过点击相应的tab实现选择,而第二层fragment和tab也拥有同样功能,即也可以滑动和选择
先上布局

  • activity_main.xml
<?xml version="1.0" encoding="utf-8"?><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/main_content"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:fitsSystemWindows="true"    tools:context="com.example.ruanyulin.tab_23.MainActivity">    <android.support.design.widget.AppBarLayout        android:id="@+id/appbar"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:paddingTop="@dimen/appbar_padding_top"        android:theme="@style/AppTheme.AppBarOverlay">        <android.support.design.widget.TabLayout            android:id="@+id/tabs"            android:layout_width="match_parent"            android:layout_height="wrap_content" />    </android.support.design.widget.AppBarLayout>    <android.support.v4.view.ViewPager        android:id="@+id/container"        android:layout_width="match_parent"        android:layout_height="match_parent"        app:layout_behavior="@string/appbar_scrolling_view_behavior" /></android.support.design.widget.CoordinatorLayout>

其中TabLayout用于显示标签tab,ViewPager用于显示fragment

  • tab1.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <TextView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:text="tab_1"        android:gravity="center"/></LinearLayout>

tab1为fragment,四个基本都一样,博主就只贴一个了

接下来是MainActivity.java

package com.example.ruanyulin.tab_23;import android.support.design.widget.TabLayout;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.Snackbar;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentPagerAdapter;import android.support.v4.view.ViewPager;import android.os.Bundle;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;public class MainActivity extends AppCompatActivity {    /**     * The {@link android.support.v4.view.PagerAdapter} that will provide     * fragments for each of the sections. We use a     * {@link FragmentPagerAdapter} derivative, which will keep every     * loaded fragment in memory. If this becomes too memory intensive, it     * may be best to switch to a     * {@link android.support.v4.app.FragmentStatePagerAdapter}.     */    private SectionsPagerAdapter mSectionsPagerAdapter;    /**     * The {@link ViewPager} that will host the section contents.     */    private ViewPager mViewPager;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //获取适配器        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());        // Set up the ViewPager with the sections adapter.        mViewPager = (ViewPager) findViewById(R.id.container);        //设置适配器,将viewpager和fragment绑定        mViewPager.setAdapter(mSectionsPagerAdapter);        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);        tabLayout.setupWithViewPager(mViewPager);    }    /**     * A placeholder fragment containing a simple view.     */    public static class PlaceholderFragment extends Fragment {        /**         * The fragment argument representing the section number for this         * fragment.         */        private static final String ARG_SECTION_NUMBER = "section_number";        public PlaceholderFragment() {        }        /**         * Returns a new instance of this fragment for the given section         * number.         */        public static PlaceholderFragment newInstance(int sectionNumber) {            PlaceholderFragment fragment = new PlaceholderFragment();            Bundle args = new Bundle();            args.putInt(ARG_SECTION_NUMBER, sectionNumber);            fragment.setArguments(args);            return fragment;        }        @Override        public View onCreateView(LayoutInflater inflater, ViewGroup container,                                 Bundle savedInstanceState) {            View view = null;            switch (getArguments().getInt(ARG_SECTION_NUMBER)){                case 1:                    view = inflater.inflate(R.layout.tab1,container,false);                    break;                case 2:                    view = inflater.inflate(R.layout.tab2,container,false);                    break;                case 3:                    view = inflater.inflate(R.layout.tab3,container,false);                    break;                case 4:                    view = inflater.inflate(R.layout.tab4,container,false);                    break;            }            return view;        }    }    /**     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to     * one of the sections/tabs/pages.     */    public class SectionsPagerAdapter extends FragmentPagerAdapter {        public SectionsPagerAdapter(FragmentManager fm) {            super(fm);        }        @Override        public Fragment getItem(int position) {            // getItem is called to instantiate the fragment for the given page.            // Return a PlaceholderFragment (defined as a static inner class below).            return PlaceholderFragment.newInstance(position + 1);        }        @Override        public int getCount() {            // Show 4 total pages.            return 4;        }        @Override        public CharSequence getPageTitle(int position) {            switch (position) {                case 0:                    return "tab 1";                case 1:                    return "tab 2";                case 2:                    return "tab 3";                case 3:                    return "tab 4";            }            return null;        }    }}

其中有两个内部类,PlaceholderFragment继承自Fragment,里面的OnCreateView函数返回fragment的视图;
SectionsPagerAdapter继承自FragmentPagerAdapter,所以他是适配器。
到这里第一层fragment已经完成了
这里写图片描述

  • 第二层
    接下来我们在tab4里面再嵌套两个fragment
    依旧创建两个tab.xml,布局和前面一样,就不贴出来了
    主要是把activity_main.xml代码复制一份贴到tab4.xml里面
    新建PlaceholderFragment_second.java
package com.example.ruanyulin.tab_23;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentPagerAdapter;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;/** * Created by ruanyulin on 17-8-14. */public class PlaceholderFragment_second extends Fragment {    /**     * The fragment argument representing the section number for this     * fragment.     */    private static final String ARG_SECTION_NUMBER = "section_number";    public PlaceholderFragment_second() {    }    /**     * Returns a new instance of this fragment for the given section     * number.     */    public static PlaceholderFragment_second newInstance(int sectionNumber) {        PlaceholderFragment_second fragment = new PlaceholderFragment_second();        Bundle args = new Bundle();        args.putInt(ARG_SECTION_NUMBER, sectionNumber);        fragment.setArguments(args);        return fragment;    }    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        View view = null;        switch (getArguments().getInt(ARG_SECTION_NUMBER)){            case 1:                view = inflater.inflate(R.layout.tab41,container,false);                break;            case 2:                view = inflater.inflate(R.layout.tab42,container,false);                break;        }        return view;    }    public static class SectionsPagerAdapter_second extends FragmentPagerAdapter {        public SectionsPagerAdapter_second(FragmentManager fm) {            super(fm);        }        @Override        public Fragment getItem(int position) {            // getItem is called to instantiate the fragment for the given page.            // Return a PlaceholderFragment (defined as a static inner class below).            return PlaceholderFragment_second.newInstance(position + 1);        }        @Override        public int getCount() {            // Show 4 total pages.            return 2;        }        @Override        public CharSequence getPageTitle(int position) {            switch (position) {                case 0:                    return "tab 41";                case 1:                    return "tab 42";            }            return null;        }    }}

其中内部类SectionsPagerAdapter_second.java为第二层的适配器
修改PlaceholderFragment.java

@Override        public View onCreateView(LayoutInflater inflater, ViewGroup container,                                 Bundle savedInstanceState) {            View view = null;            switch (getArguments().getInt(ARG_SECTION_NUMBER)){                case 1:                    view = inflater.inflate(R.layout.tab1,container,false);                    break;                case 2:                    view = inflater.inflate(R.layout.tab2,container,false);                    break;                case 3:                    view = inflater.inflate(R.layout.tab3,container,false);                    break;                case 4:                    view = inflater.inflate(R.layout.tab4,container,false);                    second_fragment = view;                    flag = 1;                    break;            }            return view;        }

最后在PlaceholderFragment.java文件里面添加如下代码

private View second_fragment;private int flag = 0;@Override        public void onActivityCreated(Bundle save) {            super.onActivityCreated(save);            if (flag == 1) {                PlaceholderFragment_second.SectionsPagerAdapter_second sectionsPagerAdapter_second;                sectionsPagerAdapter_second = new PlaceholderFragment_second.SectionsPagerAdapter_second(getChildFragmentManager());                ViewPager viewPager;                viewPager = (ViewPager) second_fragment.findViewById(R.id.container1);                //TextView textView = (TextView) tab.findViewById(R.id.tab_text42);                viewPager.setAdapter(sectionsPagerAdapter_second);                TabLayout tabLayout;                tabLayout = (TabLayout) second_fragment.findViewById(R.id.tabs1);                viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));                tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));            }        }

这样fragment嵌套就完成了
这里写图片描述

github托管:GitHub