Android Adventures - Fragments And XML
Written by Mike James   
Thursday, 27 February 2014
Article Index
Android Adventures - Fragments And XML
Blank Activity Template
Summary

Creating and using Fragments is usually a matter of working with XML layouts. Android Studio can help with this task. In this part of Android Adventures we look at how easy working with Fragments can be if you make use of the templates and other facilities provided by Android Studio. 

 

Androidgears
 

Android Adventures With Android Studio

Contents

  1. Getting Started With Android Studio
  2. The Activity And The UI
  3. Building The UI and a Calculator App
  4. Lifecycle and State
  5. Basic Controls And Events
  6. Spinners
  7. Pickers
  8. UI Graphics A Deep Dive
  9. Introducing Fragments
  10. Fragments and XML
  11. Fragment And Activity Working Together
  12. Managing Fragments
  13. Custom dialogs using DialogFragment
  14. Dialog Classes In DialogFragment
  15. A NumberPicker DialogFragment Project

 

Fragments With XML Layouts

In Introducing Android Fragments we saw how a Fragment's View hierarchy could be created in code.

Of course in most cases it is easier to use XML and in fact it is easier to get the Android Studio Designer to generate the XML for you. 

Using an XML layout with a Fragment introduces very little that is new, but it is good to see a simple example. So let's create the very simple example used in the previous chapter using the Designer. 

Start off with a new Simple Blank Activity call it xmlfrag. 

To things life easier, set the minimum SDK to 3.0 and accept the defaults.

Next navigate to the res/layout directory and right click on layout. Select New and Layout resource file. 

 

xmlfile

 

Name the file my_layout and accept the default LinearLayout as the container.

 

framentlayout

 

The new XML layout wil open in the Designer and you can use the designer to place a Button and a TextView on the layout.

 

designer

 

You can add as many XML layouts to a project as you care to and you can edit them using the Designer. 

Of course, to make use of them you have to write some code to inflate and display them and this is what we are about to do.

Select the MainActivity.java file and right click, select New, Java Class and give it the name myFragment. This is exactly what we did in the previous chapter to create a Fragment so nothing new here. 

You need to type in 

public class my_fragment extends Fragment {
}

and if you accept the correct options that appear as you type then most of the code will be generated for you. 

This again is exactly what we did in the previous chapter and now we have to define the onCreateView method. The difference is that now we are going to use the inflater passed to us to inflate the XML layout file we created:

@Override
public View onCreateView(LayoutInflater inflater,
     ViewGroup container,
     Bundle savedInstanceState) {
 View rootView = inflater.inflate(
           R.layout.my_fragment,container, false);
 return rootView;
}

This is all our Fragment needs to do.

Notice that the inflate method uses the container to work out the layout of the view hierarchy but doesn't use the container as the root. That is the container is not part of rootView. 

Finally we have to modify the activity to display the new Fragment in the usual way:

@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

if (savedInstanceState == null) {
 getFragmentManager()
       .beginTransaction()
       .add(R.id.container, new myFragment())
       .commit();
 }
}

 

The only difference here is that this time we are using a "fluent" call sequence for the FragmentManager. This is an common idiom in modern Java and it relies on the fact that getFragmentManager returns a FragmentManager object which you can use immediately by calling its beginTransaction method which returns a Transaction object which you can use immediately and so on. 

There is just one last thing to do and this is to identify the container in the main layout that the Fragment will be loaded into. To do this simply go to the activity_main.xml file and the Designer and delete the default RelativeLayout - ignore any error messages you see - and then drop a Vertical LinearLayout onto the design surface. Double click on this and enter the id 

@+id/container

Now everything should work.

If you run the program you should see a button and a TextView.

All that is left to do is wire up the UI so that when you click the button its text is transferred to the TextView as in the previous example. This has to be done in the Fragment's onCreateView event handler.

The only new feature here is the need to use findViewById to get the View objects from the inflated View hierarchy and this isn't really new as we have been doing this in the Activity since the first chapter:

Button b=
     (Button)rootView.findViewById(R.id.button);
View.OnClickListener onclick=
                     new View.OnClickListener(){
  @Override
  public void onClick(View view){
   Button bt=(Button) view;
   TextView tv=
       (TextView)getActivity().
              findViewById(R.id.textView);
   tv.setText(bt.getText());
 }
};
b.setOnClickListener(onclick);

 

Notice that to find the button you can use the rootView object''s findViewById method.

Every View object has a findViewById method but it only finds child View objects. So in the interrupt handler we can't use the Button object's findViewById to locate the TextView because it isn't a child of the Button object i.e. it isn't contained within the Button object. Instead we need to retrieve the Activity and use its findViewByID method. 

 

Putting all of this together gives for the Activity:

public class MainActivity extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState)  {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  if (savedInstanceState == null) {
   getFragmentManager()
        .beginTransaction()
        .add(R.id.container, new myFragment())
        .commit();
  }
}

and for the Fragment: 

public class myFragment extends Fragment{

@Override
public View onCreateView(LayoutInflater inflater,
      ViewGroup container,
      Bundle savedInstanceState) {
 View rootView = inflater.inflate(
            R.layout.my_fragment,container, false);
 Button b=
       (Button) rootView.findViewById(R.id.button);
 View.OnClickListener onclick=
                      new View.OnClickListener(){
   @Override
   public void onClick(View view){
    Button bt=(Button) view;
    TextView tv=(TextView)getActivity().
                       findViewById(R.id.textView);
    tv.setText(bt.getText()
   );
  }
 };
 b.setOnClickListener(onclick);
 return rootView;
}

 

Now if you run the program you will have something that works. When you click the button its text appears in the TextView.

If you have mastered the way that XML is used to create a View hierarchy using an inflater and how findViewById is used to find View objects then you should find all of this fairly obvious.



Last Updated ( Saturday, 16 August 2014 )
 
 

   
Copyright © 2014 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.