深入浅析 Android Fragment(上篇)

2019-12-10 19:59:26王旭
  • mWeixin = new ContentFragment();   }  
  • // 使用当前Fragment的布局替代id_content的控件   transaction.replace(R.id.id_content, mWeixin);  
  • break;   case R.id.tab_bottom_friend:  
  • if (mFriend == null)   {  
  • mFriend = new FriendFragment();   }  
  • transaction.replace(R.id.id_content, mFriend);   break;  
  • }   // transaction.addToBackStack();  
  • // 事务提交   transaction.commit();  
  • }   } 

    可以看到我们使用FragmentManager对Fragment进行了动态的加载,这里使用的是replace方法~~下一节我会详细介绍FragmentManager的常用API。

    注:如果使用Android3.0以下的版本,需要引入v4的包,然后Activity继承FragmentActivity,然后通过getSupportFragmentManager获得FragmentManager。不过还是建议版Menifest文件的uses-sdk的minSdkVersion和targetSdkVersion都改为11以上,这样就不必引入v4包了。

    代码中间还有两个Fragment的子类,ContentFragment上面已经见过,FriendFragment其实类似:

     

     
    1. package com.zhy.zhy_fragments;   import android.app.Fragment;  
    2. import android.os.Bundle;   import android.view.LayoutInflater;  
    3. import android.view.View;   import android.view.ViewGroup;  
    4. public class FriendFragment extends Fragment   {  
    5. @Override  public View onCreateView(LayoutInflater inflater, ViewGroup container,