Android 基础:Fragment的介绍与应用,QQ底栏,侧滑菜单

Fragment介绍

Android是在Android 3.0 (API level 11)开始引入Fragment的。可以把Fragment当成Activity的一个界面的一个组成部分,甚至Activity的界面可以完全有不同的Fragment组成,而且Fragment拥有自己的生命周期和接收、处理用户的事件,这样就不必在Activity写一堆控件的事件处理的代码了。更为重要的是,你可以动态的添加、替换和移除某个Fragment

Fragment的生命周期

因为Fragment必须嵌入在Acitivity中使用,所以Fragment的生命周期和它所在的Activity是密切相关的。
如果Activity是暂停状态,其中所有的Fragment都是暂停状态;如果Activity是stopped状态,这个Activity中所有的Fragment都不能被启动;如果Activity被销毁,那么它其中的所有Fragment都会被销毁。
但是,当Activity在活动状态,可以独立控制Fragment的状态,比如加上或者移除Fragment。
当这样进行fragment transaction(转换)的时候,可以把fragment放入Activity的back stack中,这样用户就可以进行返回操作。


Fragment的使用相关

使用Fragment时,需要继承Fragment或者Fragment的子类(DialogFragment, ListFragment, PreferenceFragment, WebViewFragment),所以Fragment的代码看起来和Activity的类似。

使用Support Library

Support Library是一个提供了API库函数的JAR文件,这样就可以在旧版本的Android上使用一些新版本的APIs。
比如android-support-v4.jar.它的完整路径是:
<sdk>/extras/android/support/v4/android-support-v4.jar.
它就提供了Fragment的APIs,使得在Android 1.6 (API level 4)以上的系统都可以使用Fragment。
为了确定没有在旧版本系统上使用新版本的APIs,需要如下导入语句:

  1. import android.support.v4.app.Fragment;      
  2.   import android.support.v4.app.FragmentManager;  

onCreateView()

 

当第一次绘制FragmentUI时系统调用这个方法,必须返回一个View,如果Fragment不提供UI也可以返回null

注意,如果继承自ListFragmentonCreateView()默认的实现会返回一个ListView,所以不用自己实现。

  1. public class ExampleFragment extends Fragment {       
  2.      @Override       
  3.      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
  4.           // Inflate the layout for this fragment           
  5.           return inflater.inflate(R.layout.example_fragment, container, false);       
  6.      }   
  7. }  

 

 Fragment加入Activity

Fragment有两种加载方式:一种是在Activitylayout中使用标签<fragment>声明;另一种方法是在代码中把它加入到一个指定的ViewGroup中。

加载方式1:通过Activity的布局文件将Fragment加入Activity

Activity的布局文件中,将Fragment作为一个子标签加入即可。

  1. <?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>  

加载方式2:通过编程的方式将Fragment加入到一个ViewGroup

Activity处于Running状态下的时候,可以在Activity的布局中动态地加入Fragment,只需要指定加入这个Fragment的父View Group即可。

  首先,需要一个FragmentTransaction实例: 

  1. FragmentManager  fragmentManager = getFragmentManager();  
  2. FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();  

 (注,如果importandroid.support.v4.app.FragmentManager;那么使用的是:FragmentManager fragmentManager = getSupportFragmentManager();


        之后,用add()方法加上Fragment的对象:

  1. ExampleFragment fragment = new ExampleFragment();    
  2. fragmentTransaction.add(R.id.fragment_container, fragment);    
  3. fragmentTransaction.commit();  

 其中第一个参数是这个fragment的容器,即父控件组。

最后需要调用commit()方法使得FragmentTransaction实例的改变生效。


Fragment简单的应用

1、新建工程

2.、创建若干个简单的布局(用于fragment的加载),如下:

            activiy_main为主布局文件,fragment1,fragment2fragment的布局文件

3、创建Fragment的类

创建Fragment1:创建过程与创建Activity类似,不过继承的是android.support.v4.app.Fragment
                   复写onCreateView函数加载fragment的布局,R.layout.fragment1就是刚刚创建的布局文件。

创建Fragment2:同上

4、运行

 

   1、与上面类似,新建布局文件activity2.xml,具体布局如下:

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:orientation="vertical" >  
  5.   
  6.     <LinearLayout  
  7.         android:id="@+id/bottom"  
  8.         android:layout_width="match_parent"  
  9.         android:layout_height="65dp"  
  10.         android:layout_alignParentBottom="true"  
  11.         android:background="@null"  
  12.         android:gravity="center_vertical"  
  13.         android:orientation="horizontal" >  
  14.   
  15.         <Button  
  16.             android:id="@+id/f1"  
  17.             android:layout_width="0dp"  
  18.             android:layout_height="50dp"  
  19.             android:layout_weight="1"  
  20.             android:text="fragment1" />  
  21.   
  22.         <Button  
  23.             android:id="@+id/f2"  
  24.             android:layout_width="0dp"  
  25.             android:layout_height="50dp"  
  26.             android:layout_weight="1"  
  27.             android:text="fragment2" />  
  28.     </LinearLayout>  
  29.   
  30.     <FrameLayout    <!--   注意,这里是帧布局不是Fragment  --!>  
  31.         android:id="@+id/content_fragment"  
  32.         android:layout_width="match_parent"  
  33.         android:layout_height="match_parent"  
  34.         android:layout_above="@+id/bottom"  
  35.         android:background="#fff" >  
  36.     </FrameLayout>  
  37.   
  38. </RelativeLayout>  

 

             两个按钮组成的布局作为底栏,上面空白部分为帧布局:

                 

 

          2、新建两个用于填充Fragment的布局文件,与上面类似。

          3、创建两个Fragment类,与上面类似

          4、编写主Activity代码:

  1. public class Activity2 extends FragmentActivity {//注意!这里继承的是FragmentActivity  
  2.     private Button f1, f2;  
  3.     private Fragment mContent; //这里是Fragment而不是帧布局,帧布局不用声明  
  4.   
  5.     @Override  
  6.     protected void onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.activity2);//加载activity的布局  
  9.         f1 = (Button) findViewById(R.id.f1);//实例化两个按钮  
  10.         f2 = (Button) findViewById(R.id.f2);  
  11.         if (mContent == null) {  
  12.             mContent = new Fragment3(); //实例化Fragment  
  13.               
  14.             //下面是重点!  
  15.           //Fragment通过FragmentManager来管理  
  16.             //beginTransaction()返回Fragment事务管理实例  
  17.             //replace()执行Fragment事务中的替换  
  18.             //R.id.content_fragment用来装载Fragment的容器  
  19.             //mContent用于替换的Fragment的对象  
  20.             //commit()提交事务,完成操作  
  21.             getSupportFragmentManager().beginTransaction().replace(  
  22.                     R.id.content_fragment, mContent).commit();  
  23.   
  24.         }  
  25.         f1.setOnClickListener(new OnClickListener() {  
  26.   
  27.             @Override  
  28.             public void onClick(View v) {  
  29.                 // TODO Auto-generated method stub  
  30.                 mContent = new Fragment3();  
  31.                 if (mContent != null) {  
  32.   
  33.                     getSupportFragmentManager().beginTransaction()  
  34.                             .replace(R.id.content_fragment, mContent).commit();  
  35.                 }  
  36.             }  
  37.         });  
  38.         f2.setOnClickListener(new OnClickListener() {  
  39.   
  40.             @Override  
  41.             public void onClick(View v) {  
  42.                 // TODO Auto-generated method stub  
  43.                 mContent = new Fragment4();  
  44.                 if (mContent != null) {  
  45.   
  46.                     getSupportFragmentManager().beginTransaction()  
  47.                             .replace(R.id.content_fragment, mContent).commit();  
  48.                 }  
  49.             }  
  50.         });  
  51.     }  
  52. }  


            5、运行调试

市场上很多应用均采取的框架,从屏幕左侧划出菜单,点击菜   单,右侧界面进行相应的切换。
    安卓5.0以前实现这种效果只能通过别人的开源代码实现,从5.0安卓开始提供了自带的侧滑菜单组件DrawerLayout,该组件在supportv4包下,兼容之前的版本。

 

 

1、新建工程,与相应的布局文件

2Activity的布局如下:

 

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <android.support.v4.widget.DrawerLayout  
  8.         android:id="@+id/drawer_layout"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="match_parent" >  
  11.   
  12.         <!-- 屏幕中的主內容 -->  
  13.   
  14.         <FrameLayout  
  15.             android:id="@+id/content_frame"  
  16.             android:layout_width="match_parent"  
  17.             android:layout_height="match_parent" />  
  18.         <!-- The navigation drawer -->  
  19.   
  20.   
  21.         <!-- 左滑菜单布局 -->  
  22.   
  23.         <LinearLayout  
  24.             android:id="@+id/left_drawer"  
  25.             android:layout_width="240dp"  
  26.             android:layout_height="match_parent"  
  27.             android:layout_gravity="start"  表示左边菜单  
  28.             android:background="#ffffff"  
  29.             android:gravity="center"  
  30.             android:orientation="vertical" >  
  31.   
  32.             <TextView  
  33.                 android:id="@+id/one"  
  34.                 android:layout_width="240dp"  
  35.                 android:layout_height="55dp"  
  36.                 android:drawableLeft="@drawable/ic_launcher"  
  37.                 android:gravity="center"  
  38.                 android:text="第一个界面"  
  39.                 android:textColor="#353535"  
  40.                 android:textSize="23dp" />  
  41.   
  42.             <TextView  
  43.                 android:id="@+id/two"  
  44.                 android:layout_width="240dp"  
  45.                 android:layout_height="55dp"  
  46.                 android:drawableLeft="@drawable/ic_launcher"  
  47.                 android:gravity="center"  
  48.                 android:text="第二个界面"  
  49.                 android:textColor="#353535"  
  50.                 android:textSize="23dp" />  
  51.   
  52.             <TextView  
  53.                 android:id="@+id/three"  
  54.                 android:layout_width="240dp"  
  55.                 android:layout_height="55dp"  
  56.                 android:drawableLeft="@drawable/ic_launcher"  
  57.                 android:gravity="center"  
  58.                 android:text="第三个界面"  
  59.                 android:textColor="#353535"  
  60.                 android:textSize="23dp" />  
  61.         </LinearLayout>  
  62.   
  63.         <!-- 增加右边抽屉显示 -->  
  64.   
  65.         <TextView  
  66.             android:id="@+id/right_drawer"  
  67.             android:layout_width="280dp"  
  68.             android:layout_height="match_parent"  
  69.             android:layout_gravity="end"  表示右边菜单  
  70.             android:background="#ffffff"  
  71.             android:gravity="center"  
  72.             android:text="@string/right_drawer_info"  
  73.             android:textColor="#444444"  
  74.             android:textSize="30sp" >  
  75.         </TextView>  
  76.     </android.support.v4.widget.DrawerLayout>  
  77.   
  78. </LinearLayout>  



3、主Acitity的编写

    1. public class MainActivity extends FragmentActivity {// 集成的是FragmentActivity  
    2.     private DrawerLayout mDrawerLayout;// 侧滑菜单  
    3.     private LinearLayout mDrawerList;// 侧滑菜单的布局  
    4.     private MenuListener menuListener;// 监听  
    5.     private TextView one, two, three;// 侧滑菜单中的三个TextView  
    6.   
    7.     @Override  
    8.     protected void onCreate(Bundle savedInstanceState) {  
    9.         super.onCreate(savedInstanceState);  
    10.         setContentView(R.layout.activity_main);  
    11.                 // 实例化操作  
    12.         mDrawerList = (LinearLayout) findViewById(R.id.left_drawer);  
    13.         mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);  
    14.         one = (TextView) findViewById(R.id.one);  
    15.         two = (TextView) findViewById(R.id.two);  
    16.         three = (TextView) findViewById(R.id.three);  
    17.         menuListener = new MenuListener();  
    18.         one.setOnClickListener(menuListener);  
    19.         two.setOnClickListener(menuListener);  
    20.         three.setOnClickListener(menuListener);  
    21.         // 设置菜单被拉出时的阴影  
    22.         mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,  
    23.                 GravityCompat.START);  
    24.         // 默认显示第一个Fragment  
    25.         Fragment fragment = new Fragment1().getNewInstance();  
    26.         FragmentManager fragmentManager = getSupportFragmentManager();  
    27.         fragmentManager.beginTransaction()  
    28.                 .replace(R.id.content_frame, fragment).commit();  
    29.     }  
    30.   
    31.     // 主要是三个TextView的监听事件  
    32.     private class MenuListener implements View.OnClickListener {  
    33.   
    34.         @Override  
    35.         public void onClick(View v) {  
    36.             // TODO Auto-generated method stub  
    37.             Fragment fragment = null;  
    38.             switch (v.getId()) {  
    39.             case R.id.one:  
    40.                 fragment = new Fragment1().getNewInstance();  
    41.   
    42.                 break;  
    43.             case R.id.two:  
    44.                 fragment = new Fragment2();  
    45.   
    46.                 break;  
    47.             case R.id.three:  
    48.                 fragment = new Fragment3();  
    49.   
    50.                 break;  
    51.             default:  
    52.                 break;  
    53.             }  
    54.             FragmentManager fragmentManager = getSupportFragmentManager();  
    55.             fragmentManager.beginTransaction()  
    56.                     .replace(R.id.content_frame, fragment).commit();  
    57.             
    58.            // 点击后关闭侧滑菜单  
    59.             mDrawerLayout.closeDrawer(mDrawerList);  
    60.         }  
    61.   
    62.     }  
    63.   
posted @ 2016-11-18 08:53  天涯海角路  阅读(184)  评论(0)    收藏  举报