public static class ExampleFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.example_fragment, //加载当前的Fragment对应的资源文件 container, //父容器控件 false); //*表明是否链接该布局和其父容器。这里设置为false,是因为系统已经插入了这个布局到父控件,设置为true将会产生多余的一个View Group*/ } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:name="com.example.news.ArticleListFragment" android:id="@+id/list" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" /> <fragment android:name="com.example.news.ArticleReaderFragment" android:id="@+id/viewer" android:layout_weight="2" android:layout_width="0dp" android:layout_height="match_parent" /> </LinearLayout>
public class BookListFragment extends ListFragment { private OnBookSelectedListener whichbook; //接口对象 public interface OnBookSelectedListener { public void onBookSelected(Integer id); //参数为Map集合的键 } ..... }(2) 然后在activity实现接口OnBookSelectedListener,在方法onBookSelected()中通知fragmentB(BookDetailFragment ),即Activity从FragmentA获取传入的ID,用来启动FragmentB。
public class SelectBookActivity extends Activity implements BookListFragment.OnBookSelectedListener { ...... public void onItemSelected(Integer id) { //a.创建Bundle,准备向Fragment传入参数 Bundle bundle=new Bundle(); bundle.putInt(BookDetailFragment.ITEM_ID, id); //装入值id到"item_id"键 //b.创建BookDetailFragment对象,并项Fragment传入参数 BookDetailFragment fragment=new BookDetailFragment(); fragment.setArguments( bundle); //c.使用fragment替换book_detail_container容器当前显示的Fragment getFragmentManager().beginTransaction() .replace(R.id.book_detail_container, fragment) .commit(); /*注释:这一句等价于.... * FragmentManager Manager=getFragmentManager(); * FragmentTransaction Transaction=Manager.beginTransaction(); * Transaction.replace(R.id.book_detail_container, Manager); * Transaction.commit(); * */ } } <span style="background-color: inherit; line-height: 1.875; font-family: 'Times New Roman';"> </span>
public void onAttach(Activity activity) { super.onAttach(activity); //a.如果Activity中没有实现Callbacks接口,抛出异常 if(!(activity instanceof Callbacks)) { throw new IllegalStateException("异常:BookListFragment所在的Activity必须实现Callback接口!"); } //把该Activity当成whichbook对象(缺少这一句话,导致出现NullPointerException错误) whichbook=( BookListFragment)activity; }(4)在fragmentA中实现onListItemClick()响应activity发出的事件(Fragment向Activity传递ID)
public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); osition).id);//激发 OnBookSelectedListener接口的onBookSelected方法 }
原文地址:http://blog.csdn.net/u012637501/article/details/46547509