https://github.com/chrisbanes/cheesesquare上找到的示例代码。我创建了CheeseListFragment的四个实例。我不明白如何访问该类的第三个实例并传递数据?特别是第三

public class MainActivity extends AppCompatActivity implements CheeseListFragment.OnDataPass {
     Adapter adapter;

...
      adapter = new Adapter(getSupportFragmentManager());

            for (int i=0; i<4; i++){
                adapter.addFragment(new CheeseListFragment(), items[i]);
            }
...

 viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                onDataPass(String.valueOf(position)); // how send data to third instance of CheeseListFragment





     static class Adapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragments = new ArrayList<>();
        private final List<String> mFragmentTitles = new ArrayList<>();



        public Adapter(FragmentManager fm) {
            super(fm);
        }

        public void addFragment(Fragment fragment, String title) {
            mFragments.add(fragment);
            mFragmentTitles.add(title);
        }

        @Override
        public Fragment getItem(int position) {


            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitles.get(position);
        }
    }
}




public class CheeseListFragment extends Fragment {

    List<News> lnews;
    private RecyclerViewAdapter mRecyclerviewAdapter;
    OnDataPass dataPasser;

...
    protected String[] mDataset;



    public interface OnDataPass {
        public void onDataPass(String data);
    }

    @Override
    public void onAttach(Activity a) {
        super.onAttach(a);
        dataPasser = (OnDataPass) a;

    }
    public void passData(String data)
        dataPasser.onDataPass(data);
    }


///////////////////////////////////////////////////// //////////////////////////

Fragment fragment = adapter.getItem(2);
CheeseListFragment cheesyFragment = (CheeseListFragment) fragment;
cheesyFragment.onDataPass(...) // how pass data?

最佳答案

您可以使用适配器中的getItem()方法获得第三个片段。对于您的情况,请致电adapter.getItem(2)

假设您不只是想添加按位置查找片段,还可以向适配器添加其他方法以按标题获取片段。

public Fragment getFragmentByTitle(String title) {
    if (!mFragmentTitles.contains(title))
        return null;

    return mFragments.get(mFragmentTitles.indexOf(title));
}


至于将数据传递给CheeseListFragment,您不必像示例代码中那样使用接口,只需将一个公共方法onDataPass()添加到CheeseListFragment类中,然后在获取片段时调用它。

09-06 18:10