//功能:点击一个按钮,显示出一个ListFragment,将ListFragment的内容给右边的Fragment显示出来//MainActivity代码:public class MainActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void clickButton(View view) { FragmentTransaction transaction = getSupportFragmentManager() .beginTransaction(); transaction.add(R.id.center, new ListFragmentDemo(), "ListFragment"); transaction.commit(); }}//继承的是ListFragment,,ListFragmentDemo中代码public class ListFragmentDemo extends ListFragment { private ArrayAdapteradapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); List list = new ArrayList (); for (int i = 0; i < 30; i++) { list.add("mike嘿嘿嘿" + i); } adapter = new ArrayAdapter (getActivity(), android.R.layout.simple_list_item_1, list); setListAdapter(adapter); // ListFragment 的好处是不用建立一个Listview,因为它内含有ListView的布局,直接绑定 } // 而且也有监听事件 @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); // 传值给另外一个Fragment // 注意这里不是getSupportFragmentManager()了,这个V4版本才有 FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); ShowListFragment showListFragment = new ShowListFragment(); transaction.add(R.id.right, showListFragment, "ShowListFragment"); // 从ListFragment获取数据 // 这里需要用到适配器获取数据,最好定义全局 String name = adapter.getItem(position); Bundle bundle = new Bundle(); bundle.putString("name", name); showListFragment.setArguments(bundle); transaction.commit(); }}public class ShowListFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { Bundle bundle = getArguments(); String name = bundle.getString("name"); TextView textView=new TextView(getActivity()); textView.setText(name); return textView; }}//主布局文件