Fragment与Activity通信 Activity向Fragment传递数据:在Activity中创建Bundle数据包,并调用Fragment的setArguments(Bundle bundle)方法即可将Bundle数据包传给Fragment. Fragment向Activity传递数据或Activity需要在Fragment运行中实时通信:在Fragment中定义一个内部回调接口,再让包含该Fragment的Activity实现该回调接口,这样Fragment即可调用该回调方法将数据传给Activity. Fragment的管理与Fragment事务(Activity管理Fragment主要依靠FragmentManager) FragmentManager可以完成如下几方面功能 1.使用findFragmentById(int id)或findFragmentByTag(String tag)方法获取指定Fragment; 2.调用popBackStack()方法将Fragment从后台栈中弹出; 3.调用addOnBackStackChangeListener()注册一个监听器,用于监听后台栈的变化. public class BookListActivity extends Activity implements BookListFragment.Callbacks { // 定义一个旗标,用于标识该应用是否支持大屏幕 private boolean mTwoPane; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 指定加载R.layout.activity_book_list对应的界面布局文件 // 但实际上该应用会根据屏幕分辨率家在不同的界面布局文件 /*屏幕适配-->创建values-sw600dp、values-large文件夹,创建refs.xml文件如下 <resources> <item type="layout" name="activity_book_list"> @layout/activity_book_twopane </item> </resources> */ setContentView(R.layout.activity_book_list); // 如果加载的界面布局文件中包含ID为book_detail_container的组件 if (findViewById(R.id.book_detail_container) != null) { mTwoPane = true; ((BookListFragment) getFragmentManager() .findFragmentById(R.id.book_list)) .setActivateOnItemClick(true); } } @Override public void onItemSelected(Integer id) { if (mTwoPane) { // 创建Bundle,准备向Fragment传入参数 Bundle arguments = new Bundle(); arguments.putInt(BookDetailFragment.ITEM_ID, id); // 创建BookDetailFragment对象 BookDetailFragment fragment = new BookDetailFragment(); // 向Fragment传入参数 fragment.setArguments(arguments); // 使用fragment替换book_detail_container容器当前显示的Fragment getFragmentManager().beginTransaction() .replace(R.id.book_detail_container, fragment).commit(); } else { // 创建启动BookDetailActivity的Intent Intent detailIntent = new Intent(this, BookDetailActivity.class); // 设置传给BookDetailActivity的参数 detailIntent.putExtra(BookDetailFragment.ITEM_ID, id); // 启动Activity startActivity(detailIntent); } } } activity_book_list.xml <!-- 直接使用BookListFragment作为界面组件 --> <fragment xmlns:android="http://schemas.android.com/apk/res/android" android:name="org.crazyit.app.BookListFragment" android:id="@+id/book_list" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="16dp" android:layout_marginRight="16dp"/> activity_book_twopane.xml <!-- 定义一个水平排列的LinearLayout,并指定使用中等分隔条 --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:divider="?android:attr/dividerHorizontal" android:showDividers="middle"> <!-- 添加一个Fragment --> <fragment android:name="org.crazyit.app.BookListFragment" android:id="@+id/book_list" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> <!-- 添加一个FrameLayout容器 --> <FrameLayout android:id="@+id/book_detail_container" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="3" /> </LinearLayout> public class BookListFragment extends ListFragment { private Callbacks mCallbacks; public interface Callbacks { public void onItemSelected(Integer id); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 为该ListFragment设置Adapter setListAdapter(new ArrayAdapter<BookContent.Book>(getActivity(), android.R.layout.simple_list_item_activated_1, android.R.id.text1, BookContent.ITEMS)); //① } // 当该Fragment被添加、显示到Activity时,回调该方法 @Override public void onAttach(Activity activity) { super.onAttach(activity); // 如果Activity没有实现Callbacks接口,抛出异常 if (!(activity instanceof Callbacks)) { throw new IllegalStateException( "BookListFragment所在的Activity必须实现Callbacks接口!"); } // 把该Activity当成Callbacks对象 mCallbacks = (Callbacks) activity; } // 当该Fragment从它所属的Activity中被删除时回调该方法 @Override public void onDetach() { super.onDetach(); // 将mCallbacks赋为null。 mCallbacks = null; } // 当用户点击某列表项时回调该方法 @Override public void onListItemClick(ListView listView , View view, int position, long id) { super.onListItemClick(listView, view, position, id); mCallbacks.onItemSelected(BookContent.ITEMS.get(position).id); } public void setActivateOnItemClick(boolean activateOnItemClick) { getListView().setChoiceMode( activateOnItemClick ? ListView.CHOICE_MODE_SINGLE : ListView.CHOICE_MODE_NONE); } } public class BookDetailActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 指定加载/res/layout目录下的activity_book_detail.xml布局文件 // 该界面布局文件内只定义了一个名为book_detail_container的FrameLayout setContentView(R.layout.activity_book_detail); // 将ActionBar上应用图标转换成可点击的按钮 getActionBar().setDisplayHomeAsUpEnabled(true); if (savedInstanceState == null) { // 创建BookDetailFragment对象 BookDetailFragment fragment = new BookDetailFragment(); // 创建Bundle对象, Bundle arguments = new Bundle(); arguments.putInt(BookDetailFragment.ITEM_ID, getIntent() .getIntExtra(BookDetailFragment.ITEM_ID, 0)); // 向Fragment传入参数 fragment.setArguments(arguments); // 将指定fragment添加到book_detail_container容器中 getFragmentManager().beginTransaction() .add(R.id.book_detail_container, fragment).commit(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { // 创建启动BookListActivity的Intent Intent intent = new Intent(this, BookListActivity.class); // 添加额外的Flag,将Activity栈中处于FirstActivity之上的Activity弹出 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 启动intent对应的Activity startActivity(intent); return true; } return super.onOptionsItemSelected(item); } } public class BookDetailFragment extends Fragment { public static final String ITEM_ID = "item_id"; // 保存该Fragment显示的Book对象 BookContent.Book book; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 如果启动该Fragment时包含了ITEM_ID参数 if (getArguments().containsKey(ITEM_ID)) { book = BookContent.ITEM_MAP.get(getArguments() .getInt(ITEM_ID)); } } // 重写该方法,该方法返回的View将作为Fragment显示的组件 @Override public View onCreateView(LayoutInflater inflater , ViewGroup container, Bundle savedInstanceState) { // 加载/res/layout/目录下的fragment_book_detail.xml布局文件 View rootView = inflater.inflate(R.layout.fragment_book_detail, container, false); if (book != null) { // 让book_title文本框显示book对象的title属性 ((TextView) rootView.findViewById(R.id.book_title)) .setText(book.title); // 让book_desc文本框显示book对象的desc属性 ((TextView) rootView.findViewById(R.id.book_desc)) .setText(book.desc); } return rootView; } } model层 public class BookContent { public static class Book { public Integer id; public String title; public String desc; public Book(Integer id, String title, String desc) { this.id = id; this.title = title; this.desc = desc; } @Override public String toString() { return title; } } public static List<Book> ITEMS = new ArrayList<Book>(); public static Map<Integer, Book> ITEM_MAP = new HashMap<Integer, Book>(); static { addItem(new Book(1, "疯狂Java讲义" , "一本全面、深入的Java学习图书,已被多家高校选做教材。")); addItem(new Book(2, "疯狂Android讲义" , "Android学习者的首选图书,常年占据京东、当当、亚马逊3大网站Android销量排行榜的榜首")); addItem(new Book(3, "轻量级Java EE企业应用实战" , "全面介绍Java EE开发的Struts 2、Spring 3、Hibernate 4框架")); } private static void addItem(Book book) { ITEMS.add(book); ITEM_MAP.put(book.id, book); } }