Android: using fragments to optimize the interface

Good afternoon. Today I would like to show you a small and fairly simple example of using Fragments. I hope it will be useful to those who have just begun to get acquainted with the principles of Fragments. Initially, fragments were implemented starting with Android 3.0 for more dynamic user interface design.
In short, Fragment is similar to Activity, they both have their own life cycle. However, a Fragment cannot exist outside an Activity. You can use different Fragments for the same Activity, which gives flexibility and variability during the development process.

More about Fragments can be found here:
Fragments. Android Developer

Let us finally turn to practice. We will write a small training program in which fragments will be used. With the vertical position of the screen, first a static list of links will be displayed and when you click on the link, an Activity will be launched that displays the contents of the web page for the selected link. When the screen is horizontal, the list of links and the contents of the web page will be placed in Fragments and displayed simultaneously. The application operation scheme is as follows:

image

Let's write the FragmentActivity class, it is from it that the application starts:

public class FragmentActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.fragment);
	}
}


Next, you need to create a layout in the fragment.xml file for the vertical and horizontal orientation of the screen, which is used in the FragmentActivity class. For horizontal orientation, we define two fragments, each will occupy half the width of the device’s screen. The contents of the /res/layout-land/fragment.xml file for horizontal screen orientation:



The contents of the file /res/layout/fragment.xml for the vertical (portrait) orientation of the screen:



We describe the layout file /res/layout/fragment_detail_activity.xml for the Activity, which will display the contents of the web page in a vertical (portrait) orientation:



The class Activity itself. In it we read the link received through extras and display the contents of the web page in the WebView. This Activity is called in vertical orientation:

public class FragmentDetailActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.fragment_detail_activity);
    	Bundle extras = getIntent().getExtras();
    String s = extras.getString("selectedValue");
    WebView viewer = (WebView) findViewById(R.id.webView1);
    viewer.loadUrl(s);
 }
}


The FragmentList class is the most voluminous, but not difficult to implement. In the onListItemClick function, we check for the presence of a FragmentDetail with a WebView. If such a fragment exists, then we call its function goToLink (String link), which loads the web page. Otherwise, if the fragment does not exist, then FragmentDetailActivity is called, to which the link is passed via extras.

public class FragmentList extends ListFragment {
     @Override
     public void onActivityCreated(Bundle savedInstanceState) {
      super.onActivityCreated(savedInstanceState);
      String[] values = new String[] {
   	 "http://mobile.tutsplus.com/tutorials/mobile-design-tutorials/80s-phone-app-slicing/",
   	 "http://mobile.tutsplus.com/tutorials/corona/create-a-brick-breaker-game-with-the-corona-sdk-game-controls/",
   	 "http://mobile.tutsplus.com/articles/news/best-of-tuts-in-february-2011/"};
      ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, values);
      setListAdapter(adapter);
     }
     @Override
     public void onListItemClick(ListView l, View v, int position, long id) {
   	 String item = (String) getListAdapter().getItem(position);
     	 FragmentDetail fragment = (FragmentDetail)getFragmentManager().findFragmentById(R.id.fragment_detail);
     	 if (fragment != null && fragment.isInLayout()) {
   		 fragment.goToLink(item);
     	 } else {
      		 Intent intent = new Intent(getActivity().getApplicationContext(), FragmentDetailActivity.class);
      		 intent.putExtra("selectedValue", item);
      		 startActivity(intent);
          }
     }    
}


We describe the FragmentDetail class; it will serve to display the contents of a web page in a WebView. In particular, the function goToLink (String link) is involved in the mapping; it is called in the FragmentList class.

public class FragmentDetail extends Fragment {
     @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container,
   	Bundle savedInstanceState) {
   	  View view = inflater.inflate(R.layout.fragment_detail, container, false);
   	  return view;
     }
     public void goToLink(String item){
   	  WebView viewer = (WebView)getView().findViewById(R.id.webView1);
   	  viewer.loadUrl(item);
     }
}


File fragment_detail.xml



That's it. Now run our application. The result of the work should be as follows:




Thank you for your attention.

UPDATE 1:
Thanks to user vtimashkov for the helpful comment found in the first comment on the article. Below is the code that solves this problem.

So, first, make the following changes to the AndroidManifest file:



This will allow us to control the change in screen orientation in the FragmentDetailActivity. Next, change the functionality of the FragmentDetailActivity class. Save the current link to the currentLink variable. The onConfigurationChanged function is called when the screen orientation is changed. In it, we check if we fell from vertical to horizontal mode, then we start FragmentActivity and pass the current link to it.

public class FragmentDetailActivity extends Activity {
	String currentLink;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_detail_activity);
		Bundle extras = getIntent().getExtras();
		currentLink = extras.getString("selectedValue");
		WebView viewer = (WebView) findViewById(R.id.webView1);
		viewer.loadUrl(currentLink);
	}	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			Intent intent = new Intent(this, FragmentActivity.class);
			intent.putExtra("selectedValue", currentLink);
			startActivity(intent);
		} 
	}
}


And finally, our FragmentActivity. First we check if we got the link in extras. If so, this means that we have switched to FragmentDetailActivity horizontal mode and now display the contents of the web page in.

public class FragmentActivity extends Activity {
@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment);
		FragmentDetail fragment = 
			(FragmentDetail)getFragmentManager().findFragmentById(R.id.fragment_detail);
		Bundle extras = getIntent().getExtras();
		if(extras != null){
				String link = extras.getString("selectedValue");
				if(link !=null && fragment != null && fragment.isInLayout()){
					fragment.goToLink(link);
				}
		}
	}
}

Also popular now: