Android中利用Fragment显示为两屏
主要是学习了下Google官方的一个小例子(http://developer.android.com/training/basics/fragments/index.html),如何在平板上显示为两屏,这个对类似于新闻类的应用比较适合,先看下效果图~
上两篇文章中是通过ViewPager的适配器FragmentPagerAdapter
, FragmentStatePagerAdapter
来使用Fragment的,我们也可以直接在Activity中使用Fragment,Android SDK v4+ Support 中为我们提供了FragmentActivity 来对Fragment进行管理,使用Fragment时需要明白的一点是,Fragment的布局文件(不管是静态布局文件还是动态创建)会被加入到容纳它的View容器中 ,还记得上一篇中动态创建Fragment时怎么创建一个返回的View吗,其中的LayoutInflater的inflate()方法就是实现了这点~
public void onArticleSelected( int position) { // The user selected the headline of an article from the HeadlinesFragment // Capture the article fragment from the activity layout // 查找文章详情Fragment ArticleFragment articleFrag = (ArticleFragment) getSupportFragmentManager().findFragmentById(R.id. article_fragment); if (articleFrag != null) { // 存在则更新详情Fragment // If article frag is available, we're in two-pane layout... // Call a method in the ArticleFragment to update its content articleFrag.updateArticleView(position); } else { // 不存在则替换为文章详情Fragment // If the frag is not available, we're in the one-pane layout and must swap frags... // Create fragment and give it an argument for the selected article ArticleFragment newFragment = new ArticleFragment(); Bundle args = new Bundle(); args.putInt(ArticleFragment. ARG_POSITION , position); newFragment.setArguments(args); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack so the user can navigate back transaction.replace(R.id. fragment_container , newFragment); transaction.addToBackStack( null ); // Commit the transaction transaction.commit(); } }