如何在viewPager的页面中使用具有不同数据的相同片段的实例?

时间:2017-10-21 21:17:57

标签: android android-fragments android-viewpager

我在viewPager中使用相同片段的不同实例。因为每个页面都做同样的事情,但只是数据不同。但问题是viewPager在所有页面中显示相同的数据。在适配器中创建新实例不会改变数据。我想要的是当用户滑动到新页面时,它会显示相应片段的新实例,如同适配器中显示的位置一样。

这是适配器:

public class FragmentPageAdapter extends FragmentPagerAdapter {

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

    @Override
    public Fragment getItem(int position) {
        if (position == 0) {
             ListViewFragment f = ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=al-jazeera-english&sortBy=top&apiKey=6cde");
            return f;
        }
        else if (position == 1){
            return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=abc-news-au&sortBy=top&apiKey=6cde");

        }

        else
        {
            return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=6cde");

        }
    }

    @Override
    public int getCount() {
        return 3;
    }
}

此活动包含viewPager:

public class WorldNews extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_world_news);


        // Find the view pager that will allow the user to swipe between fragments
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);

        // Create an adapter that knows which fragment should be shown on each page
        FragmentPageAdapter adapter = new FragmentPageAdapter(getSupportFragmentManager());

        // Set the adapter onto the view pager
        viewPager.setAdapter(adapter);
    }
}

这是Fragment的代码(只是一个实现loader的普通片段):

public class ListViewFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<GameNews>>  {
            public static ListViewFragment newInstance(String url) {
            Log.d("ListViewFragment","newInstance created");
            ListViewFragment f = new ListViewFragment();

            // Supply url input as an argument.
            Bundle args = new Bundle();
            args.putString("url", url);
            f.setArguments(args);
            return f;
        }



        private AdView mAdView;
        AdRequest adRequest;





        ListAdapter adapter ;
        private View progressBar;
        final   private int game_loader = 0;
        ArrayList<String> urls = new ArrayList<>();


        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView =  inflater.inflate(R.layout.activity_list_view, container, false);
            //Log.d("ListViewFragment","" + getArguments().getString("url"));

            mAdView = (AdView) rootView.findViewById(R.id.adView);
            adRequest = new AdRequest.Builder().build();
            mAdView.loadAd(adRequest);


            final LinearLayout emptyView = (LinearLayout) rootView.findViewById(R.id.no_internet_view);
            emptyView.setVisibility(View.INVISIBLE);

            //Getting listView
            final ListView gameListView = (ListView) rootView.findViewById(R.id.listView);

            //progress bar finding
            progressBar = rootView.findViewById(R.id.progress_bar);

            ArrayList<GameNews> gameList = new ArrayList<>();

            Button retryButton = (Button) rootView.findViewById(R.id.retry_button);

            //Making a new arrayAdapter
            adapter = new ListAdapter(getActivity(),gameList);

            //Connecting ArrayAdapter to ListView
            gameListView.setAdapter(adapter);


    urls.add(getArguments().getString("url"));
            Log.d("ListViewFragment","" + urls.get(0));

            if(isConnected())
            {
                getActivity().getLoaderManager().initLoader(game_loader, null, this);
            }

            else
            {
                emptyView.setVisibility(View.VISIBLE);
                gameListView.setVisibility(View.INVISIBLE);

            }
            //ListView item click listner
            gameListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                    GameNews currentEarthquake = adapter.getItem(i);
                    String url = currentEarthquake.getUrl();
                    final Intent intent = new Intent(getContext(), browser.class);
                    intent.putExtra("Url", url);
                    startActivity(intent);


                }
            });


            retryButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(isConnected())
                    {
                        mAdView.loadAd(adRequest);
                        getActivity().getLoaderManager().restartLoader(game_loader, null, ListViewFragment.this);
                        emptyView.setVisibility(View.INVISIBLE);
                        gameListView.setVisibility(View.VISIBLE);
                        progressBar.setVisibility(View.VISIBLE);
                        Log.d("General news","retry clicked");
                    }
                }
            });
            return rootView;

        }

        public boolean isConnected() {
            ConnectivityManager manager = (ConnectivityManager)getActivity().getSystemService(CONNECTIVITY_SERVICE);
            NetworkInfo info = manager.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                return true;
            } else {
                return false;

            }


        }

        @Override
        public Loader<List<GameNews>> onCreateLoader(int i, Bundle bundle) {
            AdManager manager =  new AdManager(getActivity());

            return new GameLoader(getActivity(),urls,1000);

        }

        @Override
        public void onLoadFinished(Loader<List<GameNews>> loader, List<GameNews> games) {
            progressBar.setVisibility(View.INVISIBLE);
            adapter.clear();

            if(games == null)
            {

                return;
            }



            adapter.addAll(games);


        }

        @Override
        public void onLoaderReset(Loader<List<GameNews>> loader) {
            adapter.clear();
        }

        public void setUrl(String url)
        {
            this.urls.add(url);

        }
        }

1 个答案:

答案 0 :(得分:0)

尝试使用FragmentStatePagerAdapter https://developer.android.com/reference/android/support/v4/app/FragmentStatePagerAdapter代替FragmentPagerAdapter。它们之间的区别:例如here