There are four types of fragments:
ListFragment
DialogFragment
PreferenceFragment
WebViewFragment
In this section, we will develop a sample application that uses these fragments. At the end of this section, the application will be completed.
This fragment is similar to ListActivity
and contains a ListView
view by default. It is used for displaying a list of items. In our previous sample code, we used ListFragment
; see the Creating and managing fragments section for ListFragment
.
This fragment displays a dialog on top of its owner activity. In the following sample application, we are going to create a fragment that has a Delete button. When the button is clicked, a DialogFragment dialog box will be displayed. The DialogFragment dialog box will have a confirmation message and two buttons – OK and Cancel buttons. If the OK button is clicked, a message will be displayed and DialogFragment will be dismissed. The screens of the sample application will look like the following screenshot:
The layout XML code of the fragment with a Delete button is shown in the following code block:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical" >
<Button
android:id="@+id/buttonFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete" />
</LinearLayout>
This layout is a simple layout with a LinearLayout
layout and a Button
component in it. The Fragment
class of this layout is as follows:
package com.chapter5; import android.app.Fragment; import android.app.FragmentTransaction; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; public class Chapter5_2Fragment extends Fragment implements OnClickListener{ Button fragmentButton; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment, container, false); fragmentButton = (Button)view.findViewById(R.id.buttonFragment); fragmentButton.setOnClickListener(this); return view; } @Override public void onClick(View v) { //we need a FragmentTransaction in order to display a dialog FragmentTransaction transaction = getFragmentManager().beginTransaction(); Chapter5_2DialogFragment dialogFragment = new Chapter5_2DialogFragment(); dialogFragment.show(transaction, "dialog_fragment"); } }
As you can see from this code, in the onClick
method of Chapter5_2Fragment
class, an instance of the Chapter5_2DialogFragment
class is created and using this instance, a dialog is displayed with its
show()
method.
The layout code of the DialogFragment dialog box is as follows:
<?xml version="1.0" encoding="utf-8"?>
<GridLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:columnCount="2"
android:orientation="horizontal" xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="@+id/textViewMessage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_columnSpan="2"
android:layout_gravity="fill"
android:text="This item will be deleted. Do you want to continue?"
android:textAppearance="?android:attr/textAppearanceLarge" />
<!—we used a linear layout here because we need it in order to evenly distribute the buttons -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_gravity="fill_horizontal"
android:layout_columnSpan="2" >
<Button
android:id="@+id/buttonOk"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="OK" />
<Button
android:id="@+id/buttonCancel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="CANCEL" />
</LinearLayout>
</GridLayout>
As you can see from this previous code, we used GridLayout
as the root layout. Then we input a TextView
component which displays the confirmation message. Finally, two buttons are added to the layout—OK and Cancel buttons. The following is the DialogFragment
class of this layout:
package com.chapter5; import android.app.DialogFragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; public class Chapter5_2DialogFragment extends DialogFragment implements OnClickListener{ Button okButton; Button cancelButton; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.dialog_fragment, container, false); //initialize the buttons and set click events okButton = (Button)view.findViewById(R.id.buttonOk) okButton.setOnClickListener(this); cancelButton = (Button)view.findViewById(R.id.buttonCancel); cancelButton.setOnClickListener(this); return view; } @Override public void onClick(View v) { if(v == cancelButton) dismiss(); else if( v == okButton) { Toast.makeText(this.getActivity(), "Item is deleted.", Toast.LENGTH_LONG).show(); dismiss(); } } }
As you the see from this code, this class extends can DialogFragment
class. In the onCreateView
method of the Chapter5_2DialogFragment
class, we initialize the buttons and set their onClick
events. In the
onClick
method of the Chapter5_2DialogFragment
class, we handle the button click events. If the clicked button is Cancel, we dismiss the dialog window. If the clicked button is OK, we show an information message and dismiss the dialog. As you can see from the preceding code, the dismiss()
method is used for closing the dialog.
This fragment is similar to PreferenceActivity
. It shows the preferences and saves them to SharedPreferences
. In this section, we will extend the previous example code. We will put a preference about showing the confirmation message during deletion. The user could be able to choose to see or not to see confirmation message. We perform the following steps for using PreferenceFragment
:
res/xml
folder:<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<CheckBoxPreference android:summary="check this in order to show confirmation message when deleting"
android:title="show confirmation message"
android:key="checkbox_preference"/>
</PreferenceScreen>
As you can see from the previous code, our preference screen contains a check box preference for the confirmation message.
PreferenceFragment
:package com.chapter5;
import android.os.Bundle;
import android.preference.PreferenceFragment;
public class Chapter5_2PereferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref);
}
}
As you can see from this code, creating a preference screen is very easy; you just call the addPreferencesFromResource
method with the XML file you created for the preferences. Now, we will in put a settings option menu item and we will open the preference screen by clicking on this menu item. In order to achieve this, we will modify the Chapter5_2Fragment
class using the following steps:
setHasOptionsMenu(true)
to the onCreateView
method of the Chapter5_2Fragment
class: @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment, container, false);
fragmentButton = (Button)view.findViewById(R.id.buttonFragment);
fragmentButton.setOnClickListener(this);
setHasOptionsMenu(true);
return view;
}
Chapter5_2Fragment
class:@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.fragment_menu, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent = new Intent(getActivity(),Chapter5_2PreferenceActivity.class); startActivity(intent); return true; }
As you can see from this code, onCreateOptionsMenu
is contributing to the options menu. This is the how a fragment contributes to the owner activity's menu. When the options menu item is clicked, a new activity is started with the onOptionsItemSelected
method.
The fragment_menu
menu XML is as follows:
<menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/itemSettings" android:title="Settings"></item> </menu>
Chapter5_2PreferenceActivity
is the class that hosts Chapter5_2PereferenceFragment
:
package com.chapter5; import android.app.Activity; import android.os.Bundle; public class Chapter5_2PreferenceActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getFragmentManager().beginTransaction() .replace(android.R.id.content, new Chapter5_2PereferenceFragment()) .commit(); } }
As you can see from this code, we programmatically add Chapter5_2PereferenceFragment
to the Chapter5_2PreferenceActivity
class.
The preference screen should look like the following screenshot:
By adding this preference option, the user has the choice of whether or not to receive the confirmation message. (To read the setting, use the standard SharedPreference
APIs.)
WebViewFragment
is a premade WebView
wrapped in a fragment. WebView
inside this fragment is automatically paused or resumed when the fragment is paused or resumed. In this section, we will extend the previous sample codes to show the usage of WebViewFragment
.
Chapter5_2Fragment
class' layout XML code. The resulting layout is as follows:<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout_fragment" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" > <Button android:id="@+id/buttonFragment" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Delete" /> <Button android:id="@+id/buttonOpenWeb" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Open Web" /> </LinearLayout>
WebViewFragment
and an activity that hosts this fragment using the following code block:package com.chapter5;
import android.os.Bundle;
import android.webkit.WebViewFragment;
public class Chapter5_2WebViewFragment extends WebViewFragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getWebView().loadUrl("http://www.google.com");
}
}
As you can see from this code, we get the WebView
instance in the onActivityCreated
method and load a URL that opens Google's website.
The activity that hosts this fragment is as follows:
package com.chapter5; import android.app.Activity; import android.os.Bundle; public class Chapter5_2WebActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getFragmentManager().beginTransaction() .replace(android.R.id.content, new Chapter5_2WebViewFragment()) .commit(); } }
As you can see from this code, we programmatically add Chapter5_2WebViewFragment
to Chapter5_2WebViewActivity
. This sample application opens the www.google.com website when the open web button is clicked.
The final version of the Chapter5_2Fragment
class is as follows:
package com.chapter5; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; public class Chapter5_2Fragment extends Fragment implements OnClickListener{ Button fragmentButton; Button openWebButton; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment, container, false); fragmentButton = (Button)view.findViewById(R.id.buttonFragment); fragmentButton.setOnClickListener(this); openWebButton = (Button)view.findViewById(R.id.buttonOpenWeb); openWebButton.setOnClickListener(this); setHasOptionsMenu(true); return view; } @Override public void onClick(View v) { if(v == fragmentButton) { FragmentTransaction transaction = getFragmentManager().beginTransaction(); Chapter5_2DialogFragment dialogFragment = new Chapter5_2DialogFragment(); dialogFragment.show(transaction, "dialog_fragment"); } else if( v == openWebButton) { Intent intent = new Intent(getActivity(),Chapter5_2WebActivity.class); startActivity(intent); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.fragment_menu, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent = new Intent(getActivity(),Chapter5_2PreferenceActivity.class); startActivity(intent); return true; } }
The main Activity
class for this application is as follows:
package com.chapter5; import android.app.Activity; import android.os.Bundle; public class Chapter5_2Activity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
This Activity
class is the owner activity of Chapter5_2Fragment
. The layout of the preceding Activity
is as follows:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout_small_a" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <fragment android:id="@+id/fragment" android:layout_width="match_parent" android:layout_height="match_parent" class="com.chapter5.Chapter5_2Fragment" /> </LinearLayout>
The AndroidManifest.xml
file of this sample application should look like the following:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.chapter5" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="15" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".Chapter5_2Activity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".Chapter5_2PreferenceActivity"></activity> <activity android:name=".Chapter5_2WebActivity"></activity> </application> </manifest>
As you can see in this code, we need Internet permission to open a website. Furthermore, we need to set the minimum SDK to API Level 14 in order to use fragments with small screens.
44.200.94.150