I have a FragmentActivity that shows the correct fragment using the ViewPager. I added a ViewPager Fragment StatePagerAdapter. If I click on a button on a fragment, it should be recreated (you need to call onCreateView again). Snippets are articles, and if the user is disconnected, I will show him "please check your network connection" and a button to reboot. A button is called a method in FragmentActivity, but I donβt know how to implement it. Maybe I can destroy and recreate the current fragment?
here is an important part of FragmentActivity:
private ArrayList<Fragment> fragments; protected void onCreate(Bundle savedInstanceState) { context = this; super.onCreate(savedInstanceState); setContentView(R.layout.activity_article_page_slider); ... pages = datahandler.getCount(...); viewPager = (ViewPager) findViewById(R.id.articlePager); PagerAdapter pagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager()); viewPager.setAdapter(pagerAdapter); viewPager.setCurrentItem(startPosition); fragments = new ArrayList<Fragment>(pages); } public void reloadData(View v) {
and the fragment itself:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { activity = getActivity(); ViewGroup rootView = (ViewGroup) inflater.inflate( R.layout.fragment_article_page, container, false); CacheDataHandler cdh = new CacheDataHandler(activity); cdh.open(); String htmlData = cdh.loadData(); rootView.findViewById(R.id.btn_reload_article_data).setVisibility(View.GONE); webView = ((WebView) rootView.findViewById(R.id.articleFragment)); refresh(); ... return rootView; } public void refresh() { ... if (htmlData == null) { rootView.findViewById(R.id.btn_reload_article_data).setVisibility(View.VISIBLE); webView.loadData(defaultdata,"text/html", "UTF-8"); } else { webView.loadData(htmlData,"text/html", "UTF-8"); } }
and fragment_article_page.xml:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <WebView android:id="@+id/articleFragment" android:layout_width="fill_parent" android:layout_height="fill_parent" /> <Button android:id="@+id/btn_reload_article_data" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:onClick="reloadData" android:text="@string/btn_txt_reload_data" android:visibility="gone" /> </RelativeLayout>
EDIT added a private ArrayList<Fragment> fragments to FragmentActivity and pass the code to control the view in the optional refresh method, look forward. Everything works fine if I click only on the first or second fragment (index 0 and 1). Otherwise, I get an IndexOutOfBoundsException . How to initialize and populate an ArrayList?
source share