如何避免使用ViewPager Android Studio创建片段的两个实例

时间:2018-08-02 14:13:49

标签: android android-fragments android-viewpager

我进行了一个选项卡式视图活动,其中有两个选项卡,当然还有两个片段。 我需要为每个片段设置标签,因为我想向它们发送数据,并且应该知道它们是否已创建(according to Deliver a message to Fragment

但是我有一个问题。目前,我在getItem方法中创建了片段的新实例并为其设置了Tag,以便在另一个位置(getCurrencies方法)检测该片段以向其发送数据。但是在getItem中,我必须创建我的片段的另一个实例并返回它,这就是问题所在! 我必须创建两个片段实例!请查看下面的代码,您将会发现。

public class DashboardActivity extends AppCompatActivity {
    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;
    List < CurrencyModel > currencies;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);
        getCurrencies();
        setSupportActionBar(toolbar);
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);

        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));


    }




    public void getCurrencies() {

        APIInterface apiInterface = APIClient.getClient().create(APIInterface.class);
        Call < GetCurrenciesModel > call = apiInterface.getCurrencies();
        call.enqueue(new Callback < GetCurrenciesModel > () {
            @Override
            public void onResponse(Call < GetCurrenciesModel > call, Response < GetCurrenciesModel > response) {

                if (response.isSuccessful()) {

                    if (response.body().getStatus() == true) {
                        currencies = new ArrayList < CurrencyModel > ();
                        for (int i = 0; i < response.body().getCurrencies().size(); i++) {

                            currencies.add(response.body().getCurrencies().get(i));


                        }

                        FeesFragment fragment = (FeesFragment) getSupportFragmentManager().findFragmentByTag("FEESFRAGMENT");
                        if (fragment != null) {

                            fragment.caller(currencies);
                        } else {

                            FeesFragment feesFragment = new FeesFragment();
                            Bundle bundle = new Bundle();
                            bundle.putParcelableArrayList("Curren", (ArrayList << ? extends Parcelable > ) currencies);
                            feesFragment.setArguments(bundle);
                            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

                            transaction.replace(R.id.fees_fragment_view, feesFragment);
                            transaction.addToBackStack(null);
                            // Commit the transaction
                            transaction.commit();


                        }



                    }


                }
            }

            @Override
            public void onFailure(Call < GetCurrenciesModel > call, Throwable t) {

            }
        });



    }

    /**
     * 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;
        }

    }

    /**
     * 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) {

            switch (position) {

                case 0:
                    return new ExchangeFragment();

                case 1:
                    Fragment feesFragment = new FeesFragment();
                    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                    fragmentTransaction.replace(R.id.fees_fragment_view, feesFragment, "FEESFRAGMENT");
                    fragmentTransaction.commit();
                    return new FeesFragment();
            }

            return null;
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 2;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在创建新实例之前,我正在检查FragmentManager中的片段实例。当PagerAdapter需要它们时,我会标记每个片段实例,并在实例化新实例之前在FragmentManager中搜索现有实例。这是我正在使用的代码。

PagerAdapter类:

private class PagerAdapter extends FragmentPagerAdapter {
    private static final int PAGE_COUNT = 3;
    private FragmentManager fragmentManager;

    private PagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
        this.fragmentManager = fragmentManager;
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = fragmentManager.findFragmentByTag("android:switcher:" +
                viewPager.getId() + ":" + getItemId(position));

        if (fragment != null) {
            return fragment;
        } else {
            switch (position) {
                case 0:
                    return FinderOrganizationsFragment.newInstance();
                case 1:
                    return FinderUsersFragment.newInstance();
                case 2:
                    return FinderBusinessesFragment.newInstance();
                default:
                    return null;
            }
        }
    }

    @Override
    public int getCount() {
        return PAGE_COUNT;
    }
}
在ViewPager中使用的每个Fragment中的

newInstance方法:

public static FinderOrganizationsFragment newInstance() {
    return new FinderOrganizationsFragment();
}