Step One
The first thing while creating your app that uses fragments is to create your layouts. Once you have created your layouts which could be a list view or anything you want, you can then create your Fragment class.
Inside your onCreateView method of your fragment, you should inflate that view – again, a list view is a good example here. You normally return a view inside this method. Now, using a list view for example, you would probably like to do something whenever a user selects an item from that list like pop open a dialog to let them confirm their actions or load a whole new view to display the details for that particular item. So, how do you accomplish that?
You simply want to implement anOnClickListener then override itsonClick method (this depends on what type of view you have – which could be a grid view or just a list view). Overriding such a method provides you with certain arguments like position – which is important when you really want to deal with particular items in a list and you can then pass the value back to the activity!
Step Two
The second step after inflating your view and implementing a click listener (as an example), you want to define an interface and then create a method – always remember than interface methods do not have bodies in them – it is the responsibility of the implementing class to override them and do what they want with them. You can define your interface from within the fragment class or as a standalone class in your project src folder.
Step Three
The third step is to implement that interface in your main activity. You will do something along the lines of MainActivity extends Activity implements FragmentOne.OnContactSelectedListener – from there on, you will have to override the method you defined earlier (from the fragment) in your activity. If your method inside your fragment expected an integer argument, remember to define it exactly as it is in your activity(same signature).
Step Four
Now that you have that covered, here comes the beauty of interfaces – whenever a user clicks an item, you can grab the position of that item (from the onClick method) and pass it back to the activity by simply calling the interface method. After that, you can pick it from the activity – inside the method you overrode and do some really awesome stuff with that position like query the database or get a value from a list array depending on which position you get back! Pretty cool right?
Let us try and create some stuff here.
MainActivity.java
/**
* The main activity that communicates with the fragments
*
*/
public class MainActivity extends Activity implements NewsItemsFragment.OnNewsItemSelectedListener
{
private NewsItemsFragment mItemsFragment;
@Override
public void onCreate(Bundle saveInstanceState)
{
super.onCreate(saveInstanceState);
setContentView(R.layout.main);
//Instantiate some stuff here like view components
mItemsFragment = new NewsItemsFragment();
//Now you can set the fragment to be visible here
setFragment(mItemsFragment);
}
public void setFragment(Fragment frag)
{
FragmentManager fm = getFragmentManager();
if (fm.findFragmentById(R.id.container) == null) {
fm.beginTransaction().add(R.id.container, frag).commit();
}
}
//Override the method here
@Override
public void onNewsItemPicked(int position)
{
//Do something with the position value passed back
Toast.makeText(activity, "Clicked "+ position, Toast.LENGTH_LONG).show();
}
}
Now we can create our Fragment class here – the order is up to you really!
NewsItemsFragment.java
1
/**
* Fragment that inflates a list view to display news headlines
* @since - 2014
*/
public class NewsItemsFragment extends ListFragment implements AdapterView.OnItemClickListener
{
Activity activity;
public static List<string> newsHeadlines = new ArrayList</string><string>(){{
add("Android Is Awesomerrrrrrrrrrrrrrrrrrr");
add("A teenager asks Miss America To Prom and gets suspended");
add("The Congress in The History of the United States is..");
add("How To Drive Safely When No One else Is.");
add("Learn How To Program On Your Own");
add("How To Communicate Between Fragments and Activities");
add("What to do when you have nothing to do");
add("The next big thing is here - your awesome app!");
}};
@Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
this.activity = activity;
}
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
ArrayAdapter</string><string> adapter = new ArrayAdapter</string><string>(activity, R.layout.simple_row_item, newsHeadlines);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
return inflater.inflate(R.layout.head_lines_fragment, container, false);
}
@Override
public void onItemClick(AdapterView< ?> parent, View view, int position, long id) {
Toast.makeText(activity, "Clicked "+ position, Toast.LENGTH_LONG).show();
try{
((OnNewsItemSelectedListener) activity).onNewsItemPicked(position);
}catch (ClassCastException cce){
}
}
public interface OnNewsItemSelectedListener{
public void onNewsItemPicked(int position);
}
}
Summary of How To communicate between fragments and activities
The reason why fragments are very powerful is because they do almost anything you would do inside an activity. That being said, you could decide to instead of passing back just theposition, you could do other manipulations like query the database to get the details from tables and then pass back the string value for the news articles. You can do a hell lot more to say the least.
As you can see, communication between fragments and activities is made so much easier through interfaces in Java and you can really do whatever you want. For example, inside the method we overrode in the activity, we could do something else like load a new fragment to display the details or even start a new intent to open a web page and other crazy things you can imagine!
This post is getting longer so I will halt it here for today and perhaps continue next time with other exciting stuff in android fragments! You can always visit the Google docs for more information on Fragments.
No comments:
Post a Comment