Tutorial details

Fragment in Android: Tutorial with Example using WebView | App Code for Sale | Preview

Fragment in Android: Tutorial with Example using WebView | Android Tutorial

How to use fragment in Android with a real example

Overview PAGE TOP

In this post we want to explain how to use fragment in Android with a real example. In the last post we talked about Fragment in Android and how we can use it to support multiple screen. We described their lifecycle and how we can use it. In this post we want to go deeper and create an example that helps us to understand better how we can use fragments. As example we want to create a simple application that is built by two fragments:

  • one that shows a list of links and
  • another one that show the web page in a WebView.

We can suppose we have two different layouts one for portrait mode and one for

landscape. In the landscape mode we want something like the image below:


while, in the portrait mode we want something like:



The first step we have to do is creating our layout. As we said we need two different layout one for portrait and one for landscape. So we have to create two xml file under res/layout (for portrait mode) and one under res/layout-land (for landscape mode). Of course we could customize more our layout including other specs but it is enough for now. These two files are called activity_layout.xml.

01  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
02      xmlns:tools="http://schemas.android.com/tools"
03      android:layout_width="match_parent"
04      android:layout_height="match_parent"
05      android:paddingBottom="@dimen/activity_vertical_margin"
06      android:paddingLeft="@dimen/activity_horizontal_margin"
07      android:paddingRight="@dimen/activity_horizontal_margin"
08      android:paddingTop="@dimen/activity_vertical_margin"
09      tools:context=".MainActivity" >
11      <fragment android:id="@+id/listFragment"
12                android:layout_width="wrap_content"
13                android:layout_height="wrap_content"
14                class="com.survivingwithandroid.fragment.LinkListFragment"/>
16  </RelativeLayout>

This one is for the portrait mode and as we notice we have only one fragment containing just the link list. We will see later how to create this fragment. We need, moreover, another layout as it is clear from the pic above, the one that contains the WebView.

01  <?xml version="1.0" encoding="utf-8"?>
03  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
05      android:layout_width="match_parent"
07      android:layout_height="match_parent"
09      android:orientation="vertical" >
11      <WebView android:id="@+id/webPage"
13               android:layout_height="wrap_content"
15               android:layout_width="wrap_content"/>
17  </LinearLayout>

For the landscape mode we have something very similar plus the FrameLayout component in the same layout.

01  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
02      xmlns:tools="http://schemas.android.com/tools"
03      android:layout_width="match_parent"
04      android:layout_height="match_parent"
05      android:paddingBottom="@dimen/activity_vertical_margin"
06      android:paddingLeft="@dimen/activity_horizontal_margin"
07      android:paddingRight="@dimen/activity_horizontal_margin"
08      android:paddingTop="@dimen/activity_vertical_margin"
09      tools:context=".MainActivity"
10      android:orientation="horizontal" >
12      <fragment android:id="@+id/listFragment"
13                android:layout_width="0dp"
14                android:layout_height="wrap_content"
15                class="com.survivingwithandroid.fragment.LinkListFragment"
16                android:layout_weight="2"/>
18      <FrameLayout android:id="@+id/fragPage"
19                   android:layout_width="0dp"
20                   android:layout_height="match_parent"
21                   android:layout_weight="4"
22                   />
24  </LinearLayout>


As you have already noticed both layout have a common fragment that is called LinkListFragment. We have to create it. If you didn’t read already the post explaining the lifecycle it is time you give a look. In this case we don’t have to override all the methods in the fragment lifecycle, but those important to control its behaviour. In our case we need to override:

  • onCreateView
  • onAttach

In this fragment we use a simple ListView to show the links and a simple adapter to customize the way how the items are shown. We don’t want to spend much time on how to create a custom adapter because it is out of this topic you can refer here to have more information. Just to remember in the onCreateView fragment method we simply inflate the layout and initialize the custom adapter.

As XML layout to inflate in the fragment we have:

01  <?xml version="1.0" encoding="utf-8"?>
02  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03      android:layout_width="match_parent"
04      android:layout_height="match_parent"
05      android:orientation="vertical" >
07      <ListView android:id="@+id/urls"
08                android:layout_height="match_parent"
09                android:layout_width="wrap_content"/>
11  </LinearLayout>

while in the method looks like:

01  @Override
02  public View onCreateView(LayoutInflater inflater, ViewGroup container,
03          Bundle savedInstanceState) {
04      Log.d("SwA", "LV onCreateView");
05      View v = inflater.inflate(R.layout.linklist_layout, container, false);
06      ListView lv = (ListView) v.findViewById(R.id.urls);
07      la = new LinkAdapter(linkDataList, getActivity());
08      lv.setAdapter(la);
09      lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
10          @Override
11           public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
12                   long id) {
13              LinkData data = ( (LinkAdapter) la ).getItem(position);
14              ( (ChangeLinkListener)  getActivity()).onLinkChange(data.getLink());
15          }
17      });
18      return v;
19  }

In this method we simply set our custom adapter and the set the listener when the user clicks on an item. We will cover this later (if you are curious see Inter fragment communication).

In the onAttach method we verify that the activity that holds the fragment implements a specific interface.

1   @Override
2       public void onAttach(Activity activity) {
3           // We verify that our activity implements the listener
4           if (! (activity instanceof ChangeLinkListener) )
5               throw new ClassCastException();
7           super.onAttach(activity);
8       }

We will clarify why we need this control later.


Basically in our example we have two fragments and they need to exchange information so that when user select an item in the fragment 1 (LinkListFragment) the other one (WebViewFragment) shows the web page corresponding to the link. So we need to find a way to let these fragments to exchange data.

On the other way we know that a fragment is a piece of code that can be re-used inside other activity so we don’t want to bind our fragment to a specific activity to not invalidate our work. In Java if we want to decouple two classes we can use an interface. So this interface solution fits perfectly. On the other hand we don’t want that our fragment exchange information directly because each fragment can rely only on the activity that holds it. So the simplest solution is that the activity implements an interface.


So in our case we define an interface called ChangeLinkListener that has only one method:

1   public interface ChangeLinkListener {
3       public void onLinkChange(String link);
4   }

We have, more over, to verify that our activity implements this interface to be sure we can call it. The best place to verify it is in the onAttach method (see above) and at the end we need to call this method when the user selects an item in the ListView:

1   lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
2       @Override
3        public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
4                long id) {
5           LinkData data = ( (LinkAdapter) la ).getItem(position);
6           (ChangeLinkListener)  getActivity()).onLinkChange(data.getLink());
7       }
9   });


By now we talked about fragments only, but we know that fragments exists inside a “father” activity that control them. So we have to create this activity but we have to do much more.

As we said before this activity has to implements a custom interface so that it can receive data from the LinkListFragment. In this method (onLinkChange) we have somehow to control if we are in landscape mode or in portrait mode, because in the first case we need to update the WebViewFragment while in the second case we have to start another activity. How can we do it? The difference in the layout is the presence of the FrameLayout. If it is present it means we are in landscape mode otherwise in portrait mode. So the code in the onLinkChange method is:

01  @Override
02  public void onLinkChange(String link) {
03      System.out.println("Listener");
04      // Here we detect if there's dual fragment
05      if (findViewById(R.id.fragPage) != null) {        WebViewFragment wvf = (WebViewFragment) getFragmentManager().findFragmentById(R.id.fragPage);
07          if (wvf == null) {
08              System.out.println("Dual fragment - 1");
09              wvf = new WebViewFragment();
10              wvf.init(link);
11              // We are in dual fragment (Tablet and so on)
12              FragmentManager fm = getFragmentManager();
13              FragmentTransaction ft = fm.beginTransaction();
15              //wvf.updateUrl(link);
16              ft.replace(R.id.fragPage, wvf);
17              ft.commit();
19          }
20          else {
21           Log.d("SwA", "Dual Fragment update");
22           wvf.updateUrl(link);
23          }
24      }
25      else {
26          System.out.println("Start Activity");
27          Intent i = new Intent(this, WebViewActivity.class);
28          i.putExtra("link", link);
29          startActivity(i);
30      }
32  }

Let’s analyse this method. The first part (line 5) verify that exists the FrameLayout. If it exists we use the FragmentManager to find the fragment relative to the WebViewFragment. If this fragment is null (so it is the first time we use it) we simply create it and put this fragment “inside” the FrameLayout (line 7-20). If this fragment already exists we simply update the url (line 23). If we aren’t in landscape mode, we can start a new activity passing data as an Intent (line 28-30).


Finally we analyze the WebViewFragment. It is really simple, it is just override some Fragment method to customize its behaviour:

01  public class WebViewFragment extends Fragment {
03      private String currentURL;
05      public void init(String url) {
06          currentURL = url;
07      }
09      @Override
10      public void onActivityCreated(Bundle savedInstanceState) {       
11          super.onActivityCreated(savedInstanceState);
12      }
14      @Override
15     public View onCreateView(LayoutInflater inflater, ViewGroup container,
16              Bundle savedInstanceState) {
18          Log.d("SwA", "WVF onCreateView");
19          View v = inflater.inflate(R.layout.web_layout, container, false);
20          if (currentURL != null) {
21              Log.d("SwA", "Current URL  1["+currentURL+"]");
23              WebView wv = (WebView) v.findViewById(R.id.webPage);
24              wv.getSettings().setJavaScriptEnabled(true);
25              wv.setWebViewClient(new SwAWebClient());
26              wv.loadUrl(currentURL);
28          }
29          return v;
30      }
32     public void updateUrl(String url) {
33          Log.d("SwA", "Update URL ["+url+"] - View ["+getView()+"]");
34          currentURL = url;
36          WebView wv = (WebView) getView().findViewById(R.id.webPage);
37          wv.getSettings().setJavaScriptEnabled(true);
38          wv.loadUrl(url);
40      }
42      private class SwAWebClient extends WebViewClient {
44          @Override
45          public boolean shouldOverrideUrlLoading(WebView view, String url) {
46              return false;
47          }
49      }
51  }

In the onCreateView method we simply inflate our layout inside the fragment and verify that the url to show is not null. If so we simply show the page (line 15-30). In the updateUrl we simply find the WebView component and update its url.

In the portrait mode we said we need to start another activity to show the webpage, so we need an activity (WebViewActivity). It is really simple and i just show the code without any other comment on it:

01  public class WebViewActivity extends FragmentActivity {
03      @Override
04      protected void onCreate(Bundle savedInstanceState) {       
05          super.onCreate(savedInstanceState);
07          WebViewFragment wvf = new WebViewFragment();
09          Intent i = this.getIntent();
10          String link = i.getExtras().getString("link");
12          Log.d("SwA", "URL ["+link+"]");
13          wvf.init(link);
14          getFragmentManager().beginTransaction().add(android.R.id.content, wvf).commit();
16      }
18  }

Reference PAGE TOP


0 Comments Leave a comment

Please login in order to leave a comment.

Newest first

to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.