简体   繁体   中英

Contents of Tabhost getting reset after switching to 3rd tab

Im developing an android app with 3 tabs. Once i'm done with fetching data from server i'm setting the text Tab1 data set success in 1st tab and new text is visible in the view. Then i switched to tab3 and switched back to tab1. Now the text is Tab 1 which is defined in tab1.xml. So how can i retain previous views contents when i'm switching between tabs.

My android code is below

public class secondPage  extends AppCompatActivity {

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_screen);
    Intent intent = getIntent();
    String dateStrig = intent.getStringExtra("Date");
    String rData = null;
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("TAB 1"));
    tabLayout.addTab(tabLayout.newTab().setText("TAB 2"));
    tabLayout.addTab(tabLayout.newTab().setText("TAB 3"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    final PagerAdapter adapter = new PagerAdapter
            (getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(adapter);

    new fetchData().execute(dateStrig);


    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });


}


public class fetchData extends AsyncTask<String, String, String> {

    Logger logger = Logger.getLogger(fetchData.class.getName());

    ProgressDialog progress;

    @Override
    protected void onPreExecute() {
        progress = new ProgressDialog(secondPage.this);
        progress.setMessage("loading...");
        progress.setCancelable(false);
        progress.show();
    }

    @Override
    protected String doInBackground(String... params) {
        String webPage = "", data = "";
        {

            try {
                URL url = new URL("http://192.168.1.101:3000/rate?date=" + params[0]);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.connect();

                InputStream is = urlConnection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));


                while ((data = reader.readLine()) != null) {
                    webPage += data + "\n";
                }

                logger.info(webPage);


            } catch (Exception e) {
                e.printStackTrace();
            }


        }
        return webPage;
    }

    protected void onPostExecute(String result) {


        TextView t1=(TextView) findViewById(R.id.textView1);
        t1.setText("Tab 1 selected");
             progress.dismiss();




    }


}
}

PageAdapter.java

public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;

public PagerAdapter(FragmentManager fm, int NumOfTabs) {
    super(fm);
    this.mNumOfTabs = NumOfTabs;
}

@Override
public Fragment getItem(int position) {

    switch (position) {
        case 0:
            Tab1 tab1 = new Tab1();
            return tab1;
        case 1:
            Tab2 tab2 = new Tab2();
            return tab2;
        case 2:
            Tab3 tab3 = new Tab3();
            return tab3;
        default:
            return null;
    }
}

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

Tab1.java

public class Tab1 extends Fragment{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.tab1, container, false);
    }
}

Tab2.java

public class Tab2 extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.tab2, container, false);
}
}

Tab3.java

public class Tab3 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.tab3, container, false);
    }
}

main_screen.xml

<android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/toolbar"
        android:background="?attr/colorPrimary"
        android:elevation="6dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:layout_below="@id/tab_layout"/>

tab1.xml

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="Tab 1"
    android:textAppearance="?android:attr/textAppearanceLarge"/>

tab2.xml and tab3.xml also looks same with different ID and text.

This is because of offscreen behaviour of ViewPager. Default is 1 try to maximise this limit as per your requirement it works for me.

_pager.setOffscreenPageLimit(10);

You can do that by using any caching techniques or using FragmentPagerAdapter instead of FragmentStatePagerAdapter . I don't prefer FragmentPagerAdapter solution because it will maintain the fragment in the memory which increase memory overheads if you get large data from the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM