Fragment

来源:互联网 发布:ubuntu共享文件夹路径 编辑:程序博客网 时间:2024/04/29 08:12

1.fragment的使用

(1)Activity布局
<span style="font-size:14px;"><span style="font-size:14px;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity"     android:orientation="horizontal"    >   <FrameLayout     android:id="@+id/fl"    android:layout_weight="1"    android:layout_width="0dp"    android:layout_height="match_parent"    ></FrameLayout> <LinearLayout        android:layout_width="wrap_content"        android:layout_height="match_parent"        android:orientation="vertical"        >        <Button             android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="fragment01"            android:onClick="click1"            />        <Button             android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="fragment02"            android:onClick="click2"            />        <Button             android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="fragment03"            android:onClick="click3"            />    </LinearLayout></LinearLayout></span></span>

(2)各个fragment的布局
a.fragment1
<span style="font-size:14px;"><span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"     android:background="#ff0000"    >    <TextView         android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="热情的红色"        android:textSize="20sp"        /></LinearLayout></span></span>
b.fragment2
<span style="font-size:14px;"><span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"     android:background="#0000ff"    >    <TextView         android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="忧桑的蓝色"        android:textSize="20sp"        /></LinearLayout></span></span>
c.fragment3
<span style="font-size:14px;"><span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"     android:background="#00ff00"    >    <TextView         android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="小志的绿色"        android:textSize="20sp"        /></LinearLayout></span></span>

(3)各个fragment的类
a. 以下重复3个
<span style="font-size:14px;"><span style="font-size:14px;">public class Fragment01 extends Fragment {//返回的view对象会作为fragment01的内容显示在屏幕上@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// TODO Auto-generated method stubView v = inflater.inflate(R.layout.fragment01, null);return v;}@Overridepublic void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);System.out.println("01create");}@Overridepublic void onStart() {// TODO Auto-generated method stubsuper.onStart();System.out.println("01start");}@Overridepublic void onResume() {// TODO Auto-generated method stubsuper.onResume();System.out.println("01resume");}@Overridepublic void onPause() {// TODO Auto-generated method stubsuper.onPause();System.out.println("01pause");}@Overridepublic void onStop() {// TODO Auto-generated method stubsuper.onStop();System.out.println("01stop");}@Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();System.out.println("01destroy");}}</span></span>

(4)使用fragment的Activity
<span style="font-size:14px;"><span style="font-size:14px;">public class MainActivity extends Activity {    private Fragment03 fg3;@Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                fg3 = new Fragment03();    //获取fragment管理器    FragmentManager fm = getFragmentManager();    //打开事务    FragmentTransaction ft = fm.beginTransaction();    //把内容显示至帧布局    ft.replace(R.id.fl, fg3);    //提交    ft.commit();    }    public void click1(View v){    //把fragment01的界面显示至帧布局中    //创建fragment对象    Fragment01 fg1 = new Fragment01();    //获取fragment管理器    FragmentManager fm = getFragmentManager();    //打开事务    FragmentTransaction ft = fm.beginTransaction();    //把内容显示至帧布局    ft.replace(R.id.fl, fg1);    //提交    ft.commit();    }        public void click2(View v){    //把fragment01的界面显示至帧布局中    //创建fragment对象    Fragment02 fg2 = new Fragment02();    //获取fragment管理器    FragmentManager fm = getFragmentManager();    //打开事务    FragmentTransaction ft = fm.beginTransaction();    //把内容显示至帧布局    ft.replace(R.id.fl, fg2);    //提交    ft.commit();    }        public void click3(View v){    //把fragment01的界面显示至帧布局中    //获取fragment管理器    FragmentManager fm = getFragmentManager();    //打开事务    FragmentTransaction ft = fm.beginTransaction();    //把内容显示至帧布局    ft.replace(R.id.fl, fg3);    //提交    ft.commit();    }}</span></span>




2.fragment的向下兼容

(1)兼容库:libs目录下android-support-v4.jar                 v4代表最低支持Android1.6
(2)导入的包为:    import android.support.v4.app.Fragment
(3)布局同上
(4)fragment代码*3
<span style="font-size:14px;">import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class Fragment01 extends Fragment {//返回的view对象会作为fragment01的内容显示在屏幕上@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// TODO Auto-generated method stubView v = inflater.inflate(R.layout.fragment01, null);return v;}}</span>

(5)Activity代码----------继承FragmentActivity
<span style="font-size:14px;">import android.os.Bundle;import android.app.Activity;import android.support.v4.app.FragmentActivity;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentTransaction;import android.view.Menu;import android.view.View;public class MainActivity extends FragmentActivity {    private Fragment03 fg3;@Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                fg3 = new Fragment03();    //获取fragment管理器    FragmentManager fm = getSupportFragmentManager();    //打开事务    FragmentTransaction ft = fm.beginTransaction();    //把内容显示至帧布局    ft.replace(R.id.fl, fg3);    //提交    ft.commit();    }    public void click1(View v){    //把fragment01的界面显示至帧布局中    //创建fragment对象    Fragment01 fg1 = new Fragment01();    //获取fragment管理器    FragmentManager fm = getSupportFragmentManager();    //打开事务    FragmentTransaction ft = fm.beginTransaction();    //把内容显示至帧布局    ft.replace(R.id.fl, fg1);    //提交    ft.commit();    }        public void click2(View v){    //把fragment01的界面显示至帧布局中    //创建fragment对象    Fragment02 fg2 = new Fragment02();    //获取fragment管理器    FragmentManager fm = getSupportFragmentManager();    //打开事务    FragmentTransaction ft = fm.beginTransaction();    //把内容显示至帧布局    ft.replace(R.id.fl, fg2);    //提交    ft.commit();    }        public void click3(View v){    //把fragment01的界面显示至帧布局中    //获取fragment管理器    FragmentManager fm = getSupportFragmentManager();    //打开事务    FragmentTransaction ft = fm.beginTransaction();    //把内容显示至帧布局    ft.replace(R.id.fl, fg3);    //提交    ft.commit();    }}</span>


3.Fragment和activity传递数据

(1)在Activity中拿到fragment的对象,调用fragment的方法传递数据
a. fragment03
<span style="font-size:14px;">public void setText(String text){tv.setText(text);}</span>

b.Activity中调用
<span style="font-size:14px;">    //把fragment01的界面显示至帧布局中    //获取fragment管理器    FragmentManager fm = getFragmentManager();    //打开事务    FragmentTransaction ft = fm.beginTransaction();    //把内容显示至帧布局    ft.replace(R.id.fl, fg3);    //提交    ft.commit();String text = et_main.getText().toString();        //传递数据    fg3.setText(text);</span>


(2)Fragment向Activity传递数据--------------------------fragment调用Activity的方法
a.不要用相同的资源id
b. MainActivity
<span style="font-size:14px;">    public void setText(String text){    et_main.setText(text);    }</span>
c.Fragment
<span style="font-size:14px;">bt.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {String text = et.getText().toString();//把数据传递给activity((MainActivity)getActivity()).setText(text);}});</span>


4. fragment的生命周期方法

<span style="font-size:14px;">public class Fragment01 extends Fragment {//返回的view对象会作为fragment01的内容显示在屏幕上@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// TODO Auto-generated method stubView v = inflater.inflate(R.layout.fragment01, null);return v;}@Overridepublic void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);System.out.println("01create");}@Overridepublic void onStart() {// TODO Auto-generated method stubsuper.onStart();System.out.println("01start");}@Overridepublic void onResume() {// TODO Auto-generated method stubsuper.onResume();System.out.println("01resume");}@Overridepublic void onPause() {// TODO Auto-generated method stubsuper.onPause();System.out.println("01pause");}@Overridepublic void onStop() {// TODO Auto-generated method stubsuper.onStop();System.out.println("01stop");}@Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();System.out.println("01destroy");}}</span>






















-------------------------------------------------------------------------Fragment--------------------------------------------------------------
转自:http://blog.csdn.net/jubincn/article/details/12856379

Fragment简介

Fragment是我们可以将Activity分成不同的组成部分,这些组成部分拥有自己的生命周期和UI。它的最大用途在于适配不同的屏幕。

创建Fragment

FragmentActivity有很多相似之处,例如可以不带UI,但这样做对两者似乎都没什么意义。他们的创建方式也很相似,例如下面的代码:
package test.fragments;import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class MySkeletonFragment extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater,  ViewGroup container,  Bundle savedInstanceState) {  // Create, or inflate the Fragment’s UI, and return it.  // If this Fragment has no UI then return null.  return inflater.inflate(R.layout.my_fragment, container, false);  }}

Fragment生命周期

Fragment的生命周期和它的宿主Activity密切相关,几乎和宿主Activity的生命周期一致,他们之间最大的不同在于Activity可以增加或删除Fragment。下图总结了Fragment的生命周期:

Fragment特有的生命周期事件

  1. Attach and detach Fragment from the parent Activity
  2. Creating and destroying Fragment
  3. Creating and Destroying UI

获取Fragment Manager

每个Activity对象都内置了一个FragmentManager对象,使用getFragmentManager()即可获得:

FragmentManager fragmentManager = getFragmentManager();

添加Fragment到Activity

在Activity中添加Fragment的最简单方法是使用layout配置文件,例如:
<?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.paad.weatherstation.MyListFragment"  android:id="@+id/my_list_fragment"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:layout_weight="1"  />  <fragment android:name="com.paad.weatherstation.DetailsFragment"  android:id="@+id/details_fragment"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:layout_weight="3"  /></LinearLayout>

调用inflate方法生成Fragment的界面后,Fragment实际上是一个类似ViewGroup的角色,在Activity中管理自己的UI。

上面那种将Fragment添加到Activity的方法缺乏灵活性,不能实现动态地添加和删除,更好的方式是使用FragmentTranaction和类似下面这样的配置文件:

<?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">  <FrameLayout  android:id="@+id/ui_container"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:layout_weight="1"  />  <FrameLayout  android:id="@+id/details_container"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:layout_weight="3"  /></LinearLayout>

使用FragmentTransaction

FragmentTransaction可以在运行时添加,删除或替换Fragment,从而实现UI的动态变化。Fragment TransactionFragment ManagerbeginTransaction()方法创建,然后可以进行Fragment的添加,删除和替换,最后通过commit()方法提交修改。

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();// Add, remove, and/or replace Fragments.// Specify animations.// Add to back stack if required.fragmentTransaction.commit();

添加,删除和替换Fragment

使用FragmentTransactionadd方法可以添加一个新的Fragmentadd()方法的主要参数是Fragment的容器View(或其ID)及Fragment实例,例如:

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();fragmentTransaction.add(R.id.ui_container, new MyListFragment());fragmentTransaction.commit();

删除Fragment需要FragmentTransaction的remove()方法,参数为Fragment对象,Fragment对象可以通过FragmentManager的findFragmentById()方法获
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();Fragment fragment = fragmentManager.findFragmentById(R.id.details_fragment);fragmentTransaction.remove(fragment);fragmentTransaction.commit();

替换Fragment使用的是FragmentTransaction的replace()方法,参数分别为所要替代Fragment所在容器的ID和新的Fragment
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();fragmentTransaction.replace(R.id.details_fragment, new DetailFragment(selected_index));fragmentTransaction.commit();

获取指定的Fragment

有两种方法可以获取某个特定的Fragment,如果这个Fragment已经被添加到某个layout文件中,则可以使用xml文件中的id作为参数:
MyFragment myFragment = (MyFragment)fragmentManager.findFragmentById(R.id.MyFragment);

也可以通过创建Fragment时添加的tag获取特定的Fragment:
MyFragment myFragment = (MyFragment)fragmentManager.findFragmentByTag(MY_FRAGMENT_TAG);

删除Fragment容器

在配置文件中将visibility的属性设为"gone",即可删除某个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">  <FrameLayout  android:id="@+id/ui_container"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:layout_weight="1"  />  <FrameLayout  android:id="@+id/details_container"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:layout_weight="3"  android:visibility="gone"  /></LinearLayout>

Fragment和Back Stack

Activity拥有Activity Stack,从而在用户按”返回”按钮时,回到前一个ActivityFragment也可以响应”返回”事件,方法是FragmentTransactioncommit之前调用addToBackStack()方法。这样,在用户按返回键后,Android会首先重现之前的UI布局。

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();fragmentTransaction.add(R.id.ui_container, new MyListFragment());Fragment fragment = fragmentManager.findFragmentById(R.id.details_fragment);fragmentTransaction.remove(fragment);String tag = null;fragmentTransaction.addToBackStack(tag);fragmentTransaction.commit();

原理和Activity类似,调用addToBackStack()后,Fragment会被push到back stack中,而不是销毁。

Fragment Transaction的动画效果

Fragment Transaction有两种方法实现动画效果,分别是:

  • 设置渐进:
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
  • 设置动画效果:
fragmentTransaction.setCustomAnimations(R.animator.slide_in_left, R.animator.slide_out_right);

Fragment和宿主Activity之间的接口

Fragment可以通过getActivity()方法获得宿主Activity对象:

TextView textView = (TextView)getActivity().findViewById(R.id.textview);

另一种常见的FragmentActivity之间的交互方式是使用回调函数:
<span style="font-size:12px">public interface OnSeasonSelectedListener {  public void onSeasonSelected(Season season);}private OnSeasonSelectedListener onSeasonSelectedListener;  private Season currentSeason;  @Override  public void onAttach(Activity activity) {  super.onAttach(activity);  try {  onSeasonSelectedListener = (OnSeasonSelectedListener)activity;  } catch (ClassCastException e) {  throw new ClassCastException(activity.toString() +"must implement OnSeasonSelectedListener");  }  }  private void setSeason(Season season) {  currentSeason = season;  onSeasonSelectedListener.onSeasonSelected(season);}</span>

没有UI的Fragment

尽管不常见,但Fragment的确是可以没有UI的,好处也许是拥有了更灵活的生命周期控制。没有UI的Fragment生命周期事件有这些:
public class NewItemFragment extends Fragment {  @Override  public void onAttach(Activity activity) {  <span style="white-space:pre"></span>super.onAttach(activity); <span style="white-space:pre"></span>// Get a type-safe reference to the parent Activity.  }  @Override    public void onCreate(Bundle savedInstanceState) {<span style="white-space:pre"></span>  super.onCreate(savedInstanceState);<span style="white-space:pre"></span>  // Create background worker threads and tasks.  }  @Override  public void onActivityCreated(Bundle savedInstanceState) {<span style="white-space:pre"></span>  super.onActivityCreated(savedInstanceState);<span style="white-space:pre"></span>  // Initiate worker threads and tasks.  }}

常用的Fragment类

  • DiagFragment
  • ListFragment
  • webViewFragment

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
-----------------------------------------------------------------------------------------------------------------
/** * 基类Fragment, 所有Fragment继承此类 *  * 1. 定义Activity常量,方便子类使用 2. 定义抽象方法initViews,初始化布局,必须实现 3. * 定义方法initData,初始化数据,可以不实现 *  * @author Kevin *  */public abstract class BaseFragment extends Fragment {public Activity mActivity;// Fragment创建@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);mActivity = getActivity();}// Fragment填充布局@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {View view = initView();return view;}/** * 初始化布局 *  * @return */public abstract View initView();// Fragment所依赖的Activity创建完成@Overridepublic void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);initData();}/** * 初始化数据 */public void initData() {}}

0 0
原创粉丝点击