应用程序打开第一个片段,有2个选项卡我想刷新第二个片段,当我移动到它但我不想刷新第一个片段
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new Main_Button(), "Main"); adapter.addFragment(new TwoFragment(), "Main2"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final ListmFragmentList = new ArrayList<>(); private final List mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } }
请解释你的答案,因为我是android的新手,我不知道我怎么能这样做
当a Fragment
可见时(即,您所选择的页面ViewPager
),将调用其setUserVisibleHint()方法.您可以覆盖该方法TwoFragment
并使用它来触发刷新.
public class TwoFragment extends Fragment { @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { // Refresh your fragment here } }
在您的片段类中使用以下代码:
@Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { getFragmentManager().beginTransaction().detach(this).attach(this).commit(); } }