建立新項目,選擇Tabbed Activityide
默認就有2個Fragment,這裏咱們刪除相關代碼。spa
在切換時
FragmentPagerAdapter
onDestroyView
onCreateView
Fragment沒有被銷燬
FragmentStatePagerAdapter
onDestroyView
onDestroy
onCreate
onCreateView
Fragment被銷燬
建議ViewPager對象使用setOffscreenPageLimit方法
建立新的Fragment而且修改代碼指針
New ->Fragment->blank Fragmentcode
FragmentPagerAdapter子類中的getItem修改以下對象
Fragment fragment = null; switch (position) { case 0: fragment=new HomeFragment(); break; case 1: fragment=new AboutFragment(); break; } return fragment;
Activity中調用Fragment對象blog
建立接口
在FragmentPagerAdapter 的instantiateItem的時候添加Fragment,ci
在destroyItem的時候刪除Fragment。rem
所有代碼get
public class MainActivity extends AppCompatActivity { public SparseArray<Fragment> fragments = new SparseArray<>(); private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ViewPager viewPager = findViewById(R.id.view_pager); viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager(),FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) { @NonNull @Override public Fragment getItem(int position) { Fragment fragment = null; switch (position) { case 0: fragment=new HomeFragment(); break; case 1: fragment=new AboutFragment(); break; } return fragment; } @Override public int getCount() { return TAB_TITLES.length; } @Nullable @Override public CharSequence getPageTitle(int position) { return getResources().getString(TAB_TITLES[position]); } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { Fragment fragment= (Fragment)super.instantiateItem(container, position); fragments.put(position,fragment); return fragment; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { fragments.remove(position); super.destroyItem(container, position, object); } }); TabLayout tabs = findViewById(R.id.tabs); tabs.setupWithViewPager(viewPager); } }
Fragment調用Activity中的方法
方法1:使用getActivity,轉成MainActivity,在調方法
方法2;在Fragment中建立Listener 接口,對象指針,設置對象的方法
public static interface onSpecialListener{ void onSL(String msg); } private onSpecialListener mListener; public void setmListener(onSpecialListener listener) { mListener=listener; }
在Activity中設置Fragment的該接口對象
fragment=new HomeFragment(); HomeFragment homeFragment=(HomeFragment)fragment; homeFragment.setmListener(new HomeFragment.onSpecialListener() { @Override public void onSL(String msg) { ShowMsg(msg); } });
在Fragment中有需求的時候調用該接口,
Button btnHome = v.findViewById(R.id.btnHome); btnHome.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mListener != null) { mListener.onSL("From HomeFragment to MainAct"); } } }); return v;