Previously, we see how to implement an endless list view adapter in Endless List view Adapter in Android. Here we are going to discuss Fragment implementation.
The Fragment represents a behavior or a portion of a user interface in an Activity. We can combine more than one fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. We can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub-activity" that you can reuse in different activities).- Referred from Google Docs
Pre-Requisites:
1. Ellipse SDK
2. Android SDK
3. ADT plugin
Or Android Studio and a compatible version of JAVA SDK
Install and configure the above utilities.
Now create a new Android project namely “FragmentExample”.
Implementation objective:
An application consists of activity and two fragments. There are two fragments will be embedded within the main activity of the application and communication implemented such that when the button in the first fragment is pressed, the text entered into the Edit Text view will appear on the text view of the second fragment using a font size ducted by the position of the seek bar in the first fragment
Creation GUI – Activity Layouts and Fragment Views:
We need
- A Relative Layout (main GUI) consists of two fragment views in it.
- A Fragment GUI (toobar_fragment) consists of Button, EditText and Seekbar in it.
- Another Fragment GUI (text_fragment) consists of TextView in it.
So, first we need to create our fragments:
For this, navigate to res/Layout/ from package explorer. And create a one layout XML
file named as toolbar_fragment.xml. And add the following code into it.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#82cafa" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/seekBar1"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:text="ChangeMessage" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:ems="10"
android:inputType="text" >
<requestFocus />
</EditText>
<SeekBar
android:id="@+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/editText1"
android:layout_marginTop="14dp" />
</RelativeLayout>
Similarly, create the second fragment named text_fragment.xml. Add following
code into it:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="TextFragment"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Now we create our main activity UI in which we embed these two fragments.
For this, navigate to res/Layout/activity_main.xml from package explorer. Open
activity_main.xml
Add the following code into it:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FragmentExampleActivity" >
<fragment
android:id="@+id/toolbar_fragment"
android:name="com.example.msclient010.fragmentexample.ToolbarFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:layout="@layout/toolbar_fragment" />
<fragment
android:id="@+id/text_fragment"
android:name="com.example.msclient010.fragmentexample.TextFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
tools:layout="@layout/text_fragment" />
</RelativeLayout>
Creating fragment classes and Implementing Communication between fragments
- Having done so it’s time to implement the fragments and bind them to our main activity So create a Java class “ToolbarFragment” and extend the Fragment class.
- The only changes to this class are to override the onCreateView() method to make sure the layout file is inflated and displayed when the fragment is used within an activity.
- When the user touches the button in the toolbar fragment, the fragment class is going to need to get the text from the EditText view and the current value of the SeekBar and send them to the text fragment
- The first step in this process is to make sure that the toolbar fragment responds to the button being clicked. We also need to implement some code to keep track of the value of the SeekBar view.
- This is because the user interface contains a SeekBar instance and the fragment needs to receive notifications when the user slides the bar to change the font size.
- Implementation of the OnSeekBarChangeListener interface requires that the onProgressChanged(), onStartTrackingTouch() and onStopTrackingTouch() methods be implemented.
- These methods have been implemented but only the onProgressChanged() method is actually required to perform a task,
in this case, storing the new value in a variable named seek_value which has been declared at the start of the class. - Also declared is a variable in which to store a reference to the EditText object.
- A method named on_Button_Click() belonging to the activity class being called when the button is clicked by the user
package com.example.msclient010.fragmentexample;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
public class ToolbarFragment extends Fragment implements SeekBar.OnSeekBarChangeListener {
//tell us seek bar progress
private static int seekvalue = 10;
//Text field
private static EditText edittext;
//Tool bar listener
ToolbarListener activityCallback;
public interface ToolbarListener{
public void onButtonClick(int position, String text);
}
@Override
public void onAttach(Activity activity){
super.onAttach(activity);
try{
//setting instance for tool bar listener
activityCallback = (ToolbarListener)activity;
}catch(ClassCastException e){
throw new ClassCastException(activity.toString() + "must implement ToolbarListener");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){ View view = inflater.inflate(R.layout.toolbar_fragment,container,false);
// getting reference of text field
edittext = (EditText) view.findViewById(R.id.editText1);
//getting reference of seek bar
final SeekBar seekBar = (SeekBar)view.findViewById(R.id.seekBar1);
//setting onSeekBarChangeListener to seek bar
seekBar.setOnSeekBarChangeListener(this);
//getting reference of button
final Button button = (Button) view.findViewById(R.id.button1);
//setting onClickListener to button
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
buttonClicked(v);
}
});
return view;
}
private void buttonClicked(View view) {
//sending value for seekbar and editText to main activity on button click
activityCallback.onButtonClick(seekvalue, edittext.getText().toString());
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//setting values for seek bar progress
seekvalue = progress;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
Similarly, create another java class called TextFragment
and extend Fragments in it.
An activity can communicate with a fragment by obtaining a reference to the fragment class instance and then calling public methods on the object.
As such, within the TextFragment class, we will now implement a public method named changeTextProperties() which takes as arguments an integer for the font size and a string for the new text to be displayed.
The method will then use these values to modify the TextView object.
package com.example.msclient010.fragmentexample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TextFragment extends Fragment {
private static TextView textView ;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View view = inflater.inflate(R.layout.text_fragment,container, false);
//getting reference of textview
textView = (TextView)view.findViewById(R.id.textView1);
return view;
}
public void changeTextProperties (int fontsize, String text)
{
//setting font size for text view
textView.setTextSize(fontsize);
//setting text in textField
textView.setText(text);
}
}
Using this ID, it is now possible for the activity to obtain a reference to the fragment instance and call the changeTextProperties() method on the object.
Edit the MainActivity.java file and modify the onButtonClick() method as follows:
package com.example.msclient010.fragmentexample;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity implements ToolbarFragment.ToolbarListener { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onButtonClick(int fontsize, String text) {
//getting TextFragment reference
TextFragment textFragment = (TextFragment)getSupportFragmentManager().findFragmentById(R.id.text_fragment); //setting text and size in textFragment
textFragment.changeTextProperties(fontsize,text);
}
}
Running the application:
Hit on the Run button, you see two fragments on the screen:
The first fragment is in blue color because of background-color property which is set to light blue in its Layout XML:
Next, type your message in the Text field of the first fragment and click on “ChangeMessage” button, we see the message in the second fragment.
Our message’s font size is very small because of the seekbar progress.
Just slide the seek bar in the forward direction this results from the increase in the font-size value of the text message in the second fragment.
Thanks for reading this post.
Happy Coding!!J
Leave Comment