且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Fragment例子 .

更新时间:2022-09-04 20:52:06

Fragment翻译为碎片,功能和Activity类似,依赖于父Activity,有自己独立的声明周期,用来描述一些行为或一部分用户界面,在一个Activity中你可以合并多个fragment,在一个单独的activity中建立多个UI面板,同时重用fragment在多个activity中使用.你可以认为fragment作为一个activity中的一子模块 ,接收自己的输入事件,你可以向运行中的activity添加或移除fragment。两个Activity通过两个Fragment合并到一个Activity的布局方式.

下面上例子:

效果图:

Fragment例子 .

首先创建main.xml为第一启动页面

在一个activity的布局文件中嵌入两个fragment:

<?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.jiayuan.fragment.fragmentImp.FirstFragment"   
           
android:id="@+id/firstFragment"   
            android:layout_weight="1"   
            android:layout_width="0dp"   
            android:layout_height="match_parent"   
            />   
    <fragment
android:name="com.jiayuan.fragment.fragmentImp.SecondFragment"   
           
android:id="@+id/secondFragment"   
            android:layout_weight="2"   
            android:layout_width="0dp"   
            android:layout_height="match_parent"   
            />  

              
     <Button android:id="@+id/btn_1"  
        android:layout_width="wrap_content"   
        android:layout_height="wrap_content"  
        android:text="隐藏"  
     />   
     <Button android:id="@+id/btn_2"  
        android:layout_width="wrap_content"   
        android:layout_height="wrap_content"  
        android:text="隐藏"  
     />   
</LinearLayout>

这样就把两个fragment嵌入到了使用该布局文件的activity中。 和普通的Veiw没有区别。这样也就有一个好处是,布局文件可以重复使用(类似include)。需要说明的是嵌入的Fragment存在于Activity的ViewGroup中,注意main.xml中的两个fragment 绿色区域为是指向了你定的FirstFragment类,该类要继承Fragment,在该类中要维护fragement的声明周期方法, android:id="@+id/firstFragment",是该fragement的唯一标识,另一种定义fragment的标识的方法是android:tag="@+id/firstFragment"两种定义方式在通过FragementManager获取某个fragment的时候有点区别

分别使用getFragmentManager().findFragmentById(id);

getFragmentManager().findFragmentByTag(id);

FragmentManager:

可以使用FragmentManager来管理Fragment。在Activity中通过getFragmentManager来获得。FragmentManager 类一些主要的方法有通过findFragmentById()来获取一个Activity中有关Fragment布局。
当然还有类似findFragmentByTag()方法,以及当Fragment中出栈的popBackStack()同时可以注册 addOnBackStackChangedListener()管理。具体的可以在android.app.FragmentManager类中了解。
可以使用FragmentManager进行事物处理。通过begintransaction方法获取一个事物处理实例。
FragmentTransaction transaction = fragmentManager.beginTransaction();
在这期间可以使用 add(), remove()和replace()。最终需要改变时执行 commit()。

然后创建两个fragment的布局文件first.xml和second.xml,其实这两个布局文件和activity文件第一完全相同,这个就随意定义两个

frist.xml

<?xml
 version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="hello,你是美女?" />
</LinearLayout>

second.xml

<?xml
 version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="sorry,我是丑男...." />
</LinearLayout>


在然后定义两个fragement的实现类FirstFragment.java和SecondFragment.java

1、FirstFragment.java

package com.jiayuan.fragment.fragmentImp;

import android.app.Fragment;  
import android.os.Bundle;  
import android.view.ContextMenu;  
import android.view.LayoutInflater;  
import android.view.Menu;  
import android.view.MenuItem;  
import android.view.View;  
import android.view.ViewGroup;  
import android.view.ContextMenu.ContextMenuInfo;  
  
public class FirstFragment extends Fragment{  
  
      
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
    }  
    
    
    //绘制视图
    public View onCreateView(LayoutInflater inflater, ViewGroup container,   
                             Bundle savedInstanceState) {  
        View root = inflater.inflate(R.layout.first, container, false);  
        registerForContextMenu(root.findViewById(R.id.editText1));  
        return root;   
    }   
      
      
    @Override  
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {  
        super.onCreateContextMenu(menu, v, menuInfo);  
        menu.add(Menu.NONE, 0, Menu.NONE, "菜单1");  
        menu.add(Menu.NONE, 1, Menu.NONE, "菜单2");  
    }  
  
    @Override  
    public boolean onContextItemSelected(MenuItem item) {  
        return super.onContextItemSelected(item);  
    }  
      
}  


2、SecondFragment.java

package com.jiayuan.fragment.fragmentImp;


import android.app.Fragment;  
import android.os.Bundle;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.ViewGroup;  
  
public class SecondFragment extends Fragment{  
  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        // TODO Auto-generated method stub  
        super.onCreate(savedInstanceState);  
    }  
      
    public View onCreateView(LayoutInflater inflater, ViewGroup container,   
            Bundle savedInstanceState) {   
        return inflater.inflate(R.layout.second, container, false);   
    }   
}

做几点说明:


1、你可以在fragement的实现方法的onCreate生命周期方法中使用res/layout/xxx.xml文件,就像activity一样。

2、如果你显示的为列表,那么你就可以使用PreferenceFragment来实现,它里封装了ListView用作列表显示。其使用的布局文件为res/xml/xxx.xml

3、当系统调用fragment在首次绘制用户界面时,如果画一个UI在你的fragment你必须返回一个View当然了你可以返回null代表这个fragment没有UI.

在然后是在activity中使用

TestFragmentActivity.java

package com.jiayuan.frament.activity;
import android.app.Activity;  
import android.app.Fragment;  
import android.app.FragmentManager;  
import android.app.FragmentTransaction;  
import android.os.Bundle;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  
  
public class TestFragmentActivity extends Activity {  
    /** Called when the activity is first created. */  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
          
//        FirstFragment firstFragment=new FirstFragment();  
//        //在Activity中通过这个与Fragment通讯  
//        getFragmentManager().beginTransaction().add(android.R.id.content, firstFragment).commit();  
          
        FragmentManager fm = getFragmentManager();  
        addShowHideListener(R.id.btn_1, fm.findFragmentById(R.id.firstFragment));  
        addShowHideListener(R.id.btn_2, fm.findFragmentById(R.id.secondFragment));  
          
    }  
      
    void addShowHideListener(int buttonId, final Fragment fragment) {  
        final Button button = (Button)findViewById(buttonId);  
        button.setOnClickListener(new OnClickListener() {  
            public void onClick(View v) {  
                FragmentTransaction ft = getFragmentManager().beginTransaction();  
                //为Fragment设置淡入淡出效果  
                ft.setCustomAnimations(android.R.animator.fade_in,android.R.animator.fade_out);  
                          
                if (fragment.isHidden()) {  
                    ft.show(fragment);  
                    button.setText("隐藏");  
                } else {  
                    ft.hide(fragment);  
                    button.setText("显示");  
                }  
                ft.commit();  
            }  
        });  
    }       
} 

描述一下fragement的生命周期

生命周期图:

Fragment例子 .

1、从这个图里面可以看出,fragment的声明周期方法并不像activity那样容易理解

2、一个fragment必须总是嵌入在一个activity中,同时fragment的生命周期受activity而影响

3、这是activity和fragment的回调顺序:

activity.onCreate
  fragment.onAttach
  fragment.onCreate
activity.onStart
  fragment.onActivityCreated
  fragment.onStart
activity.onResume
  fragment.onResume
  fragment.onStop
activity.onStop
  fragment.onDestroyView
  fragment.onDestroy
  fragment.onDetach
activity.onDestroy

4、当activity 暂停,那么所有在这个activity的fragments将被destroy释放。 你可以在activity的不同生命周期中,对fragment执行不同操作