Name technique for passing data from fragment/activity to fragment/activity with interfaces

后端 未结 3 851
庸人自扰
庸人自扰 2021-01-26 03:48

At school we\'re now learning on how to make fragments more universal by using interfaces. This technique is still kinda abstract and I don\'t really know when/how to use it.

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-26 04:19

    Here are steps:

    1. Download sample data from http://developer.android.com/training/basics/fragments/index.html(given in right side) and also look at url to how to add fragments from xml or dynamically to performing fragment transaction operations..

    2. Then would recommend you to go through with fragment guide..http://developer.android.com/guide/components/fragments.html

    3. Once you understand complete life cycle and its fragment callback methods then would be easy to understand example given by Google as sample.

    4. To defining interface in fragment to calling interface or passing callback to activity..

    5. Let’s say you have two fragments which shows list as article titles and article details.

    6. In your article list extends fragment list public class Fragment1 extends ListFragment
    7. Set your list view using list adapter in oncreateview method.

      ArrayAdapter adapter = new ArrayAdapter(getActivity(),
      android.R.layout.simple_list_item_1, Array);
      setListAdapter(adapter);
      
    8. Now we need to display article details when user click on article, so we need to pass position to activity to it can call back corresponding article details to show in fragment2.
    9. So when user click on article, system call onListItemClick callback method.

      public void onListItemClick(ListView l, View v, int position, long id) {
      super.onListItemClick(l, v, position, id);
      

      Call interface here and pass article position

    10. Define interface and pass position in method which activity will override.

      public interface OnArticleSelectedListener {
      public void onArticleSelected(int position);
      }
      
    11. In on attach method instantiates an instance of interface by casting the Activity, If the activity has not implemented the interface, then the fragment throws a ClassCastException. On success.

    12. Override interface method to display article details by passing position as bundle data to Fragment2.

    Hope it will help you to understand sample code.

提交回复
热议问题