美文网首页
Fragment的一些知识点

Fragment的一些知识点

作者: 纸狒 | 来源:发表于2019-06-21 16:43 被阅读0次

    内容概述:

      1,fragment的使用
    
      2,fragment的生命周期
    
      3,fragment间的通信
    

    fragment被称为五大组件之一的原因:

    1,从使用频率上来讲,fragment不输其他组件

    2,有自己的生命周期

    3,可以灵活地加载到activity中去,但是必须依附于activity


    一,fragment的使用

    1,fragment加载到activity的两种方式

    2,fragmentPagerAdapter与fragmentStatePagerAdapter的区别

    3,fragment的add(),replace(),remove()方法


    1.1 Fragment加载到activity中的两种方法

    1,静态加载

    添加fragment到activity的布局文件中去
    

    2,动态加载

    通过fragmentManager和fragmentTransaction来动态加载fragment
    

    动态加载步骤

    1,添加fragmentTransaction的实例

    2,用add()方法加上fragment对象oneFragment

    3,调用commit()方法获得fragmentTansaction实例的改变生效。

    1.代码例子如下:

     假设要实现的效果如下:
     即一个homeActivity下四个fragment:
      Homefragment,
      CategoryFragment,
      CommunityFragment,
      MineFragment
    
    image

    1,布局(activity_main)

    
    <?xml version="1.0" encoding="utf-8"?>
    
        xmlns:android="http://schemas.android.com/apk/res/android"
    
        android:orientation="vertical"
    
        android:layout_width="match_parent"
    
        android:layout_height="match_parent"
    
        android:background="@color/white">
    
            android:id="@+id/pager"
    
            android:layout_width="wrap_content"
    
            android:layout_height="wrap_content"
    
            android:layout_alignBottom="@+id/view">
    
            android:id="@+id/content_layout"
    
            android:layout_width="match_parent"
    
            android:layout_height="match_parent"
    
            android:layout_above="@+id/linearLayout" />
    
                android:id="@+id/linearLayout"
    
                android:layout_width="match_parent"
    
                android:layout_height="wrap_content"
    
                android:layout_alignParentBottom="true"
    
                android:background="@android:color/white"
    
                android:orientation="horizontal"
    
                android:paddingBottom="4dp"
    
                android:paddingTop="4dp">
    
                    android:id="@+id/home_layout_view"
    
                    android:layout_width="wrap_content"
    
                    android:layout_height="wrap_content"
    
                    android:layout_weight="1">
    
                        android:id="@+id/home_image_view"
    
                        android:layout_width="wrap_content"
    
                        android:layout_height="wrap_content"
    
                        android:layout_centerHorizontal="true"
    
                        android:background="@drawable/ic_home" />
    
                        android:id="@+id/tv_home"
    
                        android:layout_width="wrap_content"
    
                        android:layout_height="wrap_content"
    
                        android:layout_below="@id/home_image_view"
    
                        android:layout_centerHorizontal="true"
    
                        android:layout_marginTop="4dp"
    
                        android:text="首页"
    
                        android:textSize="10sp"
    
                        android:textColor="@color/color_333333"/>
    
                    android:id="@+id/category_layout_view"
    
                    android:layout_width="wrap_content"
    
                    android:layout_height="wrap_content"
    
                    android:layout_weight="1">
    
                        android:id="@+id/category_image_view"
    
                        android:layout_width="wrap_content"
    
                        android:layout_height="wrap_content"
    
                        android:layout_alignParentTop="true"
    
                        android:layout_centerHorizontal="true"
    
                        android:layout_marginTop="0dp"
    
                        android:background="@drawable/ic_sale_fill" />
    
                        android:id="@+id/tv_categorye"
    
                        android:layout_width="wrap_content"
    
                        android:layout_height="wrap_content"
    
                        android:layout_centerHorizontal="true"
    
                        android:layout_marginTop="4dp"
    
                        android:text="分类"
    
                        android:textSize="10sp"
    
                        android:textColor="@color/color_333333"
    
                        android:layout_below="@id/category_image_view"/>
    
                    android:id="@+id/write_layout_view"
    
                    android:layout_width="wrap_content"
    
                    android:layout_height="wrap_content"
    
                    android:layout_weight="1">
    
                        android:id="@+id/write_image_view"
    
                        android:layout_width="40dp"
    
                        android:layout_height="40dp"
    
                        android:background="@drawable/ic_add"
    
                        android:layout_centerInParent="true"/>
    
                    android:id="@+id/message_layout_view"
    
                    android:layout_width="wrap_content"
    
                    android:layout_height="wrap_content"
    
                    android:layout_weight="1">
    
                        android:id="@+id/message_image_view"
    
                        android:layout_width="28dp"
    
                        android:layout_height="28dp"
    
                        android:background="@drawable/ic_plant"
    
                        android:layout_centerHorizontal="true"/>
    
                        android:id="@+id/tv_person"
    
                        android:layout_width="wrap_content"
    
                        android:layout_height="wrap_content"
    
                        android:layout_centerHorizontal="true"
    
                        android:layout_marginTop="4dp"
    
                        android:text="社区"
    
                        android:textSize="10sp"
    
                        android:textColor="@color/color_333333"
    
                        android:layout_below="@id/message_image_view"/>
    
                    android:id="@+id/mine_layout_view"
    
                    android:layout_width="wrap_content"
    
                    android:layout_height="wrap_content"
    
                    android:layout_weight="1">
    
                        android:id="@+id/mine_image_view"
    
                        android:layout_width="wrap_content"
    
                        android:layout_height="wrap_content"
    
                        android:background="@drawable/ic_mine"
    
                        android:layout_centerHorizontal="true"/>
    
                        android:id="@+id/tv_mine"
    
                        android:layout_width="wrap_content"
    
                        android:layout_height="wrap_content"
    
                        android:layout_centerHorizontal="true"
    
                        android:layout_marginTop="4dp"
    
                        android:text="我的"
    
                        android:textSize="10sp"
    
                        android:textColor="@color/color_333333"
    
                        android:layout_below="@id/mine_image_view"/>
    
            android:layout_width="match_parent"
    
            android:layout_height="0.2dp"
    
            android:layout_above="@id/linearLayout"
    
            android:background="@color/color_cccccc"
    
            android:id="@+id/view" />
    
    </RelativeLayout>
    
    

    HomeActivity.java的代码如下

    public class HomeActivity extends BaseActivity implements
            View.OnClickListener{
      //fragment类
        private HomeFragment mHomefragment;
        private CategoryFragment mCategoryfragment;
        private CommunityFragment mCommunityfragment;
        private MineFragment mMinefragment;
    
        private FragmentManager fm;
    
    
        private RelativeLayout mHomeLayout;
        private RelativeLayout mMineLayout;
        private RelativeLayout mCategroyLayout;
        private RelativeLayout mCommunityLayout;
        private RelativeLayout mWriteLayout;
    
        private TextView mHomeView;
        private TextView mMineView;
        private TextView mCategroyView;
        private TextView mCommunityView,mWriteView;
    
     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_home_layout);
            //初始化视图
            initView();
      mHomefragment=new HomeFragment();
    //        fm = getFragmentManager();//因为fragment是3.0以后才出现的组件,为了让之前的的版本也可以使用,所以才有了getSupportFragmentManager();
            fm = getSupportFragmentManager();//主要用于支持3.0以下的版本,3.0以上的可以直接调用
            FragmentTransaction fragmentTransaction=fm.beginTransaction();
            fragmentTransaction.replace(R.id.content_layout,mHomefragment);
            fragmentTransaction.commit();
       }
    private void hideFragment(Fragment fragment, FragmentTransaction ft) {
            if (fragment != null) {
                ft.hide(fragment);
            }
        }
      //初始化视图
        @SuppressLint("ResourceAsColor")
        public void initView(){
            setStatusBar();
            changeStatusBarColor(R.color.white);
            statusBarLightMode(HomeActivity.this);
            //statusBarLightMode(HomeActivity.this,1);
            mHomeLayout=(RelativeLayout)findViewById(R.id.home_layout_view);
            mHomeLayout.setOnClickListener(this);
    
            mMineLayout=(RelativeLayout)findViewById(R.id.mine_layout_view);
            mMineLayout.setOnClickListener(this);
    
            mCategroyLayout = (RelativeLayout)findViewById(R.id.category_layout_view);
            mCategroyLayout.setOnClickListener(this);
    
            mMessageLayout = (RelativeLayout)findViewById(R.id.message_layout_view);
            mMessageLayout.setOnClickListener(this);
    
            mWriteLayout = (RelativeLayout)findViewById(R.id.write_layout_view);
            mWriteLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mHomeView.setBackgroundResource(R.drawable.ic_home);
                    mMineView.setBackgroundResource(R.drawable.ic_mine);
                    mCategroyView.setBackgroundResource(R.drawable.ic_sale_fill);
                    mMessageView.setBackgroundResource(R.drawable.ic_plant);
                    mWriteView.setBackgroundResource(R.drawable.ic_add_selected);
                    showselect();
    
                }
            });
    
    
            mHomeView=(TextView)findViewById(R.id.home_image_view);
            mMineView=(TextView)findViewById(R.id.mine_image_view);
            mCategroyView =(TextView) findViewById(R.id.category_image_view);
            mMessageView =(TextView) findViewById(R.id.message_image_view);
            mWriteView = (TextView)findViewById(R.id.write_image_view);
    
            mHomeView.setBackgroundResource(R.drawable.ic_home_select);
    
    
        }
    @Override
        public void onClick(View v) {
    
            FragmentTransaction fragmentTransaction = fm.beginTransaction();
            switch (v.getId()) {
                case R.id.home_layout_view:
    //                viewPager.setCurrentItem(0);
    
                    mHomeView.setBackgroundResource(R.drawable.ic_home_select);
                    mMineView.setBackgroundResource(R.drawable.ic_mine);
                    mCategroyView.setBackgroundResource(R.drawable.ic_sale_fill);
                    mMessageView.setBackgroundResource(R.drawable.ic_plant);
    //                mWriteView.setBackgroundResource(R.drawable.ic_add);
                    hideFragment(mCategoryfragment, fragmentTransaction);
    //                hideFragment(mfragment,fragmentTransaction);
                    hideFragment(mMessagefragment, fragmentTransaction);
                    hideFragment(mMinefragment, fragmentTransaction);
                    if (mHomefragment == null) {
                        mHomefragment = new HomeFragment();
                        fragmentTransaction.add(R.id.content_layout, mHomefragment);
                    } else {
                        mcurrent = mHomefragment;
                        fragmentTransaction.show(mHomefragment);
                    }
                    break;
    
                case R.id.category_layout_view:
    //                viewPager.setCurrentItem(1);
    
                    mHomeView.setBackgroundResource(R.drawable.ic_home);
                    mMineView.setBackgroundResource(R.drawable.ic_mine);
                    mCategroyView.setBackgroundResource(R.drawable.ic_sale_select);
                    mMessageView.setBackgroundResource(R.drawable.ic_plant);
    
                    hideFragment(mHomefragment, fragmentTransaction);
                    hideFragment(mMessagefragment, fragmentTransaction);
                    hideFragment(mMinefragment, fragmentTransaction);
                    if (mCategoryfragment == null) {
                        mCategoryfragment = new CategoryFragment();
                        fragmentTransaction.add(R.id.content_layout, mCategoryfragment, "Category");
                    } else {
                        mcurrent = mCategoryfragment;
                        fragmentTransaction.show(mCategoryfragment);
                    }
    
                    break;
    
                case R.id.message_layout_view:
    //                viewPager.setCurrentItem(2);
    
                    mHomeView.setBackgroundResource(R.drawable.ic_home);
                    mMineView.setBackgroundResource(R.drawable.ic_mine);
                    mCategroyView.setBackgroundResource(R.drawable.ic_sale_fill);
                    mMessageView.setBackgroundResource(R.drawable.ic_planted);
    
                    hideFragment(mHomefragment, fragmentTransaction);
                    hideFragment(mCategoryfragment, fragmentTransaction);
                    hideFragment(mMinefragment, fragmentTransaction);
                    if (mMessagefragment == null) {
                        mMessagefragment = new MessageFragment();
                        fragmentTransaction.add(R.id.content_layout, mMessagefragment);
                    } else {
                        mcurrent = mMessagefragment;
                        fragmentTransaction.show(mMessagefragment);
                    }
                    break;
    
                case R.id.mine_layout_view:
    
                    mHomeView.setBackgroundResource(R.drawable.ic_home);
                    mMineView.setBackgroundResource(R.drawable.ic_mine_select);
                    mCategroyView.setBackgroundResource(R.drawable.ic_sale_fill);
                    mMessageView.setBackgroundResource(R.drawable.ic_plant);
    
    //                viewPager.setCurrentItem(3);
                    hideFragment(mHomefragment, fragmentTransaction);
                    hideFragment(mMessagefragment, fragmentTransaction);
                    hideFragment(mCategoryfragment, fragmentTransaction);
                    if (mMinefragment == null) {
                        mMinefragment = new MineFragment();
                        fragmentTransaction.add(R.id.content_layout, mMinefragment);
                    } else {
                        mcurrent = mMinefragment;
                        fragmentTransaction.show(mMinefragment);
                    }
                    break;
            }
            fragmentTransaction.commit();
        }
    
    }
    
    

    3,其他fragment就有fragment该有的布局,举一个简单的例子
    MineFragment.java

    public class MineFragment extends Basefragment{
      @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }
     @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            mContentView=inflater.inflate(R.layout.fragment_mine_layout, container, false);
            return  mContentView;
        }
    }
    
    

    2,ViewPager+Fragment的代码例子如下:
    由上面的效果图可知,例子是HomeFragment包着三个fragment
    HomeFragment的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:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white">
        <!--导航条-->
        <RelativeLayout
    
            android:layout_marginTop="25dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/white"
            android:padding="10dp">
    
            <!--菜单垂直居中,且放在右手边-->
            <TextView
                android:id="@+id/category_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_alignParentRight="true"
                android:background="@drawable/ic_calendar"/>
    
            <TextView
                android:id="@+id/search_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_toLeftOf="@id/category_view"
                android:background="@drawable/bg_home_edittext"
                android:gravity="center"
                android:padding="6dp"
                android:text="请输入"
                android:textColor="@color/color_cdcdcd"
                android:textSize="16sp"/>
        </RelativeLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1">
                <TextView
                    android:layout_centerInParent="true"
                    android:id="@+id/recommendPage"
                    android:layout_centerVertical="true"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="首页"
                    android:textColor="@color/color_cccccc"
                    android:gravity="center"
                    android:textSize="16dp" />
                <View
                    android:layout_centerHorizontal="true"
                    android:id="@+id/line_one"
                    android:layout_below="@+id/recommendPage"
                    android:layout_marginTop="10dp"
                    android:layout_width="32dp"
                    android:layout_height="2dp"
                    android:background="@color/colorPrimary"
                    android:visibility="invisible"/>
            </RelativeLayout>
    
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1">
        <TextView
            android:layout_centerInParent="true"
            android:id="@+id/newPage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
    
            android:gravity="center"
            android:layout_centerVertical="true"
            android:textColor="@color/color_cccccc"
            android:text="新作"
            android:textSize="16dp" />
        <View
            android:layout_centerHorizontal="true"
            android:id="@+id/line_two"
            android:layout_below="@+id/newPage"
            android:layout_marginTop="10dp"
            android:layout_width="32dp"
            android:layout_height="2dp"
            android:layout_marginLeft="5dp"
    
            android:background="@color/colorPrimary"
            android:visibility="invisible"
            />
    </RelativeLayout>
            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1">
                <TextView
                    android:layout_centerInParent="true"
                    android:id="@+id/Guess"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
    
                    android:gravity="center"
                    android:layout_centerVertical="true"
                    android:textColor="@color/color_cccccc"
                    android:text="猜你喜欢"
                    android:textSize="16dp" />
                <View
                    android:layout_centerHorizontal="true"
                    android:id="@+id/line_three"
                    android:layout_below="@+id/Guess"
                    android:layout_marginTop="10dp"
                    android:layout_width="32dp"
                    android:layout_height="2dp"
                    android:layout_marginLeft="5dp"
    
                    android:background="@color/colorPrimary"
                    android:visibility="invisible"
                    />
            </RelativeLayout>
    
        </LinearLayout>
        <RelativeLayout
            android:id="@+id/fail_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scaleType="center"
            android:layout_marginTop="150dp"
            android:layout_gravity="center"
            android:visibility="gone">
            <!--过渡动画-->
            <ImageView
                android:id="@+id/loading_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@android:color/white"
               android:layout_centerVertical="true"
                android:layout_centerHorizontal="true"
                android:src="@drawable/ic_home"
    
                />
            <TextView
                android:id="@+id/wrong_message"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="加载失败"
                android:layout_below="@+id/loading_view"
                android:layout_marginTop="50dp"
                android:layout_gravity="center"
                android:textSize="16dp"
                android:textColor="@color/color_333333"/>
        </RelativeLayout>
    
        <RelativeLayout
            android:id="@+id/viewpager_content_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="visible">
            <!--该布局在linearLayout上面-->
            <android.support.v4.view.ViewPager
                android:id="@+id/viewpager"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/view"
                >
            </android.support.v4.view.ViewPager>
        </RelativeLayout>
    
    
    </LinearLayout>
    

    HomeFragment.java

    public class HomeFragment extends Basefragment
            implements View.OnClickListener , ViewPager.OnPageChangeListener {
        private View mContentView;
        protected Activity mContext;
    
        private List<Fragment> fragmentList;
        private ViewPager viewPager;
    
        private FragmentStateAdapter adapter1;
    
        private TextView mRecommandView;
        private TextView mNewView,mGuessView;
        private TextView mHomeView;
    
        private View mRecommandLine;
        private View mNewLine,mGuessLine;
    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }
    
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            mContext=getActivity();
            mContentView=inflater.inflate(R.layout.fragment_home_layout, container, false);
            initView();
            return  mContentView;
        }
        public Context getContext() {
            if (mContext == null) {
                return AdminApplication.getInstance();
            }
            return mContext;
        }
        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            mContext = getActivity();
        }
        private void initView() {
    
            viewPager=(ViewPager)mContentView.findViewById(R.id.viewpager);
            viewPager.setOnPageChangeListener((ViewPager.OnPageChangeListener) this);
            mNewView =(TextView)mContentView.findViewById(R.id.newPage);
            mNewView.setOnClickListener(this);
            mRecommandView =(TextView)mContentView.findViewById(R.id.recommendPage);
            mRecommandView.setOnClickListener(this);
            mGuessView =(TextView)mContentView.findViewById(R.id.Guess);
            mGuessView.setOnClickListener(this);
    
            mRecommandLine = (View) mContentView.findViewById(R.id.line_one);
            mNewLine = (View) mContentView.findViewById(R.id.line_two);
            mGuessLine = (View) mContentView.findViewById(R.id.line_three);
    
            mRecommandView.setTextColor(this.getResources().getColor(R.color.colorPrimary));
            mNewView.setTextColor(getResources().getColor(R.color.color_333333));
            mGuessView.setTextColor(getResources().getColor(R.color.color_333333));
            mRecommandLine.setVisibility(View.VISIBLE);
            mNewLine.setVisibility(View.INVISIBLE);
                    /**
             * 通过fragment作为ViewPager的数据源
             */
            fragmentList=new ArrayList<Fragment>();
            fragmentList.add(new RecommandFragment());
            fragmentList.add(new newFragment());
            fragmentList.add(new GuessFragment());
    
    
            adapter1=new FragmentStateAdapter(getChildFragmentManager(),fragmentList);
            viewPager.setAdapter(adapter1);
            viewPager.setCurrentItem(0);
    
            mHomeView =(TextView)mContentView.findViewById(R.id.search_view);
            mHomeView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mContext, SearchActivity.class);
                    mContext.startActivity(intent);
                }
            });
    
        }
    
        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.recommendPage:
                    viewPager.setCurrentItem(0);
                    break;
                case R.id.newPage:
                    viewPager.setCurrentItem(1);
                    break;
                case R.id.Guess:
                    viewPager.setCurrentItem(2);
                    break;
            }
    
        }
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    
        }
    
    
        @SuppressLint("ResourceAsColor")
        @Override
        public void onPageSelected(int position) {
            switch (position) {
                case 0:
                    mRecommandView.setTextColor(this.getResources().getColor(R.color.colorPrimary));
                    mNewView.setTextColor(getResources().getColor(R.color.color_333333));
                    mGuessView.setTextColor(getResources().getColor(R.color.color_333333));
                    mRecommandLine.setVisibility(View.VISIBLE);
                    mNewLine.setVisibility(View.INVISIBLE);
                    mGuessLine.setVisibility(View.INVISIBLE);
    //                Toast.makeText(mContext,"推荐",Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    mRecommandView.setTextColor(this.getResources().getColor(R.color.color_333333));
                    mNewView.setTextColor(getResources().getColor(R.color.colorPrimary));
                    mRecommandLine.setVisibility(View.INVISIBLE);
                    mNewLine.setVisibility(View.VISIBLE);
                    mGuessView.setTextColor(getResources().getColor(R.color.color_333333));
                    mGuessLine.setVisibility(View.INVISIBLE);
    //                Toast.makeText(mContext,"新上映",Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    mRecommandView.setTextColor(this.getResources().getColor(R.color.color_333333));
                    mNewView.setTextColor(getResources().getColor(R.color.color_333333));
                    mRecommandLine.setVisibility(View.INVISIBLE);
                    mNewLine.setVisibility(View.INVISIBLE);
                    mGuessView.setTextColor(getResources().getColor(R.color.colorPrimary));
                    mGuessLine.setVisibility(View.VISIBLE);
                    break;
            }
        }
    
        @Override
        public void onPageScrollStateChanged(int state) {
    
        }
    }
    

    FragmentStateAdapter.java

    public class FragmentStateAdapter extends FragmentStatePagerAdapter {
        private List<Fragment> fragmentList;
        public FragmentStateAdapter(FragmentManager fm, List<Fragment> fragmentList) {
            super(fm);
            this.fragmentList= fragmentList;
        }
    
        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }
    
        @Override
        public int getCount() {
            return fragmentList.size();
        }
    
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            return super.instantiateItem(container, position);
        }
    
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            super.destroyItem(container, position, object);
        }
    }
    
    

    1.2,fragmentPagerAdapter与fragmentStatePagerAdapter的区别

    ** 1. fragmentPagerAdapter:**使用于页面较少的情况,以保存内存,这样处理也对系统内存不会造成太多影响

    源码中:destoryItem()方法中,

                      mCurrentTransaction.detach((Fragment)Object)
    
                    此方法把fragment的UI与activity的UI脱离开来
    
                    但是该方法并不回收内存
    

    2,fragmentStateAdapter:使用于页面较多的情况,因为在切换页面的过程中,使用这个方法,它是回收内存的。因为页面越多,会越消耗内存。

    源码中:destroyItem()方法中

                      mCurrentTransaction.remove(fragment)
    
                      调用的是remove方法,即真正是释放了内存
    
                      可以回收内存
    

    1.3 fragment的add(),replace(),remove()方法

    从上面的例子可以看出:
    add()就是增加fragment
    replace()就是替换fragment,前面的代码的onCreate()里面的要用replace()是因为本来就已经有静态加载的布局文件了,用于替换,最后变成动态加载fragment
     remove()就是移除fragment
    

    二,fragment的生命周期

      (加深为fragment,不加深为activity的周期),由上而下时一个流程
    
        开始创建fragment对象
    

    onAttach():表明fragment与activity关联后回调

    接着开启**onCreate():这是fragment的onCreate方法,表示初次创建fragment,但这个时候还没有创建完成

    onCreateView():绘制界面了

    onViewCreated():fragment的UI已经绘制好,可初始化控件资源了

      此时调用Activity-onCreate()
    

    onActivityCreate():这是fragment的

      Activity-onStart()
    

    onStart():fragment可见了

      Activity-onResume():activity可交互了
    

    onResume():此时fragment也可交互了

    此时的fragment完全初始化完毕

    当fragment进入onPause()状态时

    activity-onPause()

    onStop()

    activity-onStop()

    onDestroyView()

    onDestroy()

    onDetach() fragment对象被销毁

    Activity -onDestroy()

    总结:

    onAttach():表明fragment与activity关联后回调

    onCreate():这是fragment的onCreate方法,表示初次创建fragment,但这个时候还没有创建完成

    onCreateView():绘制界面了

    onViewCreated():fragment的UI已经绘制好,可初始化控件资源了

    onActivityCreate():这是fragment的

    onStart():fragment可见了

    onResume():此时fragment也可交互了

    onPause()

    onStop()

    onDestroyView()

    onDestroy()

    onDetach() fragment对象被销毁

    三,fragment通信

    1,在fragment中调用Activity的中的方法, getActivity

    2,在Activity中调用fragment中的方法,接口回调

    3,在fragment中调用fragment中的方法,findFragmentById

    4,扩展:github上找到的分类筛选菜单,源码中包含了以上几种类型关于它具体例子的实现方法,特别具体
    https://github.com/Krupen/FabulousFilter

    例子:

    1,在frament中调用Activity

          Activity mContext =getActivity();
    

    例子

     EditText editText = (EditText) getActivity().findViewById(R.id.editText);
    

    3,在Activity中调用fragment(接口回调)
    ①可以用findFragmentById();
    例子:

    //使用场景:我觉得是静态加载的时候可以这么用,
    FragmentManager manager = this.getSupportFragmentManager();
    fragment = (MyFragment) manager.findFragmentById(R.id.fragment1);
    

    ②可以使用findFragmentByTag();

    FragmentManager manager = this.getSupportFragmentManager();
    fragment = (MyFragment) manager.findFragmentByTag("Fragment");
    

    但以上都要使用接口回调
    以下内容转载自https://www.cnblogs.com/smyhvae/p/4000390.html
    模拟场景:
    fragment里面进行操作,然后影响到Activity里面去,原博是fragment中修改文本,activity调用文本信息进行toast的显示
    在fragment.java的里面定义接口回调

    一定要为editText加一个id,不然会报空指针异常的错误;

    添加一个接口回调,用于获取文本的值,然后稍后再Activity当中进行调用。

     //接口回调
        public void getEditText(CallBack callBack) {
            String msg = editText.getText().toString();
            callBack.getResult(msg);
        }
    
        public interface CallBack {
            public void getResult(String result);
        }
    

    在activity中设置button的点击事件

    button.setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    //点击按钮后,通过接口回调,获取fragment当中EditText的值,并弹出吐司
                    leftFragment.getEditText(new CallBack(){
                        @Override
                        public void getResult(String result) {
                            // TODO Auto-generated method stub
                            Toast.makeText(MainActivity.this, result, 1).show();
                        }                    
                    });
                }
            });
    

    3,在fragment中调用fragment

        findFragmentById();
    
        findFragmentByTag();
    

    例子:毕设菜单+常规使用

        代码如下:
    

    在添加fragment时,即它的上一层,也就是HomeActivity下

     fragmentTransaction.add(R.id.content_layout, mCategoryfragment, "Category");
    

    毕设菜单当时查找时
    子fragment

     MySampleFabFragment dialogFrag;
    
     dialogFrag.show(getActivity().getSupportFragmentManager(), dialogFrag.getTag());
    

    正常情况下

    //在这个fragmentA(要调用Categoryfragment)
    Categoryfragment fragment  = (Categoryfragment) getSupportFragmentManager().findFragmentByTag("Category");
    //示例:假如Categoryfragment有一个方法show(),用于给字符串赋值,其实在这里,也可以调用Categoryfragment的控件,然后给它赋值或者获取值
    String a = fragment.show();//1
    EditText editText = (EditText) fragment.getView().findViewById(R.id.editText2);//获取EditText的输入值
    

    补充知识点:

    问:请问getActivity和getContext的详细区别

    答:首先Activity和Application都是Context的子类
    Context从字面上理解就是上下文的意思,在实际应用中它也确实是起到了管理上下文环境中各个参数和变量的总用,方便我们可以简单的访问到各种资源。
    虽然Activity和Application都是Context的子类,但是他们维护的生命周期不一样。前者维护一个Acitivity的生命周期,所以其对应的Context也只能访问该activity内的各种资源。后者则是维护一个Application的证明周期。

    源于:https://ask.csdn.net/questions/270675

    问:getChildFragmentManager和getsupportFragmentManager和getFragmentManager的关系

    答:1,getChildFragmentManager()所得到的是在fragment里面的子容器的管理者。
    场景:Homefragment下两个fragment,homefragment要调用管理者,用的就是getChildFragmentManager();
    2, getsupportFragmentManager():主要用于支持3.0以下的版本,3.0以上的可以直接调用
    3,getFragmentManager()因为fragment是3.0以后才出现的组件,为了让之前的的版本也可以使用,所以才有了getSupportFragmentManager();

    源于:https://blog.csdn.net/baidu_40389775/article/details/86179692

    相关文章

      网友评论

          本文标题:Fragment的一些知识点

          本文链接:https://www.haomeiwen.com/subject/vqkuqctx.html