In the post Tab Layout in Android with ActionBar and Fragment the fragments can’t be replaced later, in this post I write the changes in order to replace the first fragment of the first tab with a third fragment using a button at runtime.
It is very easy to get the Context inside an Activity:
- with the getApplicationContext() method
- using only “this” because the Activity class extends the Context class
But you can’t use any of these two methods inside a Fragment and you have to replace them respectively with:
I often do this replacement when I use code written for an Activity, but that I must use in a Fragment.
In the post Tabs and swipe views Szymon asks how to implement a WebView in order to preserve its state moving from one tab to another in a similar way as explained in How to save the state of a WebView inside a Fragment of an Action Bar.
The idea for this post came to me after reading the comment of Esthon Wood: “do you have any idea on how to save the state of the WebView? I mean, the webview refreshes everytime I tap on the tab.” in the post Tab Layout in Android with ActionBar and Fragment.
In the post Tab Layout in Android with ActionBar and Fragment I wrote an example about tabs in an action bar where each label open a fragment that you can not change at runtime.
In this post I explain how to replace a fragment with an other using a button.
I thought of writing a post about how to save the position of a ScrollView when I read the Bhavin’s comment in the post Tab Layout in Android with ActionBar and Fragment.
Bhavin asked how one could restore the position of a scrollview switching between a tab and the other.
In a previous post I wrote an example of Layout Tab using a TabActivity class that it is deprecated since version 3.0 Honeycomb of Android.
In this post I develop the same interface using ActionBar and Fragment, and I tried wherever possible to limit the changes to the files *.xml.