原文地址:点击打开链接

首先,如果你想在android3.0及以下版本使用fragment,你必须引用android-support-v4.jar这个包

然后你写的activity不能再继承自Activity类了,而是要继承android.support.v4.app.FragmentActivity,一些其他的父类也有相应的变化.

由于在android的实现机制中fragment和activity会被分别实例化为两个不相干的对象,他们之间的联系由activity的一个成员对象fragmentmanager来维护.fragment实例化后会到activity中的fragmentmanager去注册一下,这个动作封装在fragment对象的onAttach中,所以你可以在fragment中声明一些回调接口,当fragment调用onAttach时,将这些回调接口实例化,这样fragment就能调用各个activity的成员函数了,当然activity必须implements这些接口,否则会包classcasterror


fragment和activity的回调机制又是OOP的一次完美演绎!

下面通过一个例子来说明:

我把Activity的UI分为两个部分,左边和右边,左边用来放置点击的按钮(LeftFragment),右边用来放置对应点击后显示的信息(RightFragment).

Activity的布局layout文件:main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="horizontal">        <LinearLayout        android:id="@+id/left_layout"        android:layout_width="wrap_content"        android:layout_height="fill_parent"        android:layout_weight="1"        android:orientation="vertical">     </LinearLayout>       <LinearLayout        android:id="@+id/right_layout"        android:layout_width="wrap_content"        android:layout_height="fill_parent"        android:layout_weight="10"        android:orientation="vertical">     </LinearLayout>   </LinearLayout>

LeftFragment的布局layout:leftfragment.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">        <Button        android:id="@+id/first_button"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="firstButton"/>        <Button        android:id="@+id/second_button"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="second_button"/>        <Button        android:id="@+id/third_button"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="third_button"/>    </LinearLayout>

RightFragment的布局layout:rightfragment.xml

<?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">        <TextView        android:id="@+id/right_show_message"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:background="@android:color/holo_orange_dark"        android:textColor="@android:color/white"/>    </LinearLayout>

以上是两个fragment和一个Activity的布局文件,下面来看他们的java文件

Activity:

package com.example.fragmentandactivity;import com.example.fragmentandactivity.LeftFragment.MyListener;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.widget.TextView;public class MainActivity extends FragmentActivity implements MyListener{ /** 得到RightFragment中显示信息的控件 */      private TextView showMessageView;    /**      * 实现MyListener,当LeftFragment中点击第一页的时候,让RightFragment显示第一页信息,同理当点击第二页的时候,RightFragment显示第二页信息      *       * @param index       *            显示的页数       */  public void showMessage(int index)       {          if(1 == index)               showMessageView.setText("第一页");          if(2 == index)               showMessageView.setText("第二页");          if(3 == index)               showMessageView.setText("第三页");      } @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main); System.out.println("Activity--->onCreate");    FragmentManager manager = getSupportFragmentManager(); FragmentTransaction transaction = manager.beginTransaction();   // 动态增加Fragment           RightFragment rightFragment = new RightFragment();        LeftFragment leftFragment = new LeftFragment();          transaction.add(R.id.left_layout, leftFragment, "leftfragment");          transaction.add(R.id.right_layout, rightFragment, "rightfragment");          transaction.commit();  }  @Override      protected void onResume()       {          super.onResume();          System.out.println("Activity--->onResume");          showMessageView = (TextView) findViewById(R.id.right_show_message);       } @Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}

LeftFragment:

package com.example.fragmentandactivity;import android.app.Activity;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.Button;public class LeftFragment extends Fragment{   private MyListener myListener;    private Button firstButton;       private Button secondButton;       private Button thirdButton;         /** Fragment第一次附属于Activity时调用,在onCreate之前调用 */      @Override      public void onAttach(Activity activity)       {          super.onAttach(activity);          System.out.println("LeftFragment--->onAttach");               myListener = (MyListener) activity;       }          @Override      public void onCreate(Bundle savedInstanceState)       {          super.onCreate(savedInstanceState);          System.out.println("LeftFragment--->onCreate");      }          @Override      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)      {          System.out.println("LeftFragment--->onCreateView");          return inflater.inflate(R.layout.leftfragment, container, false);      }         @Override      public void onResume()       {          super.onResume();          System.out.println("LeftFragment--->onResume");               firstButton = (Button) getActivity().findViewById(R.id.first_button);           secondButton = (Button) getActivity().findViewById(R.id.second_button);           thirdButton = (Button) getActivity().findViewById(R.id.third_button);                MyButtonClickListener clickListener = new MyButtonClickListener();           firstButton.setOnClickListener(clickListener);          secondButton.setOnClickListener(clickListener);          thirdButton.setOnClickListener(clickListener);      }             /** 按钮的监听器 */      class MyButtonClickListener implements OnClickListener       {          public void onClick(View v)           {              Button button = (Button) v;               if(button == firstButton)                   myListener.showMessage(1);              if(button == secondButton)                   myListener.showMessage(2);              if(button == thirdButton)                   myListener.showMessage(3);          }      }   /** Acitivity要实现这个接口,这样Fragment和Activity就可以共享事件触发的资源了 */      public interface MyListener       {          public void showMessage(int index);       }  }

RightFragment:

package com.example.fragmentandactivity;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class RightFragment extends Fragment{ @Override      public void onCreate(Bundle savedInstanceState)       {          System.out.println("RightFragment--->onCreate");          super.onCreate(savedInstanceState);      }    @Override      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)      {          System.out.println("RightFragment--->onCreateView");          return inflater.inflate(R.layout.rightfragment, container, false);      }  }


注意,Fragment的生命周期和Activity生命周期之间的关系。在Activity里动态生成Fragment,首先是Activity调用onCreate()方法,但是这时候还没有加载到Fragment里的组件,当Fragment调用其onCreateView()方法后,Activity才能得到Fragment中的组件

这里最关键的就是Fragment要有一个接口和这个接口的引用,而这个接口需要Activity去实现它。当Fragment调用onAttach(Activity acitivity)方法的时候,将这个activity传递给这个接口引用,这样,就可以和Activity进行交互了.


更多相关文章

  1. 调用startactivityforresult后,onactivityresult响应
  2. Android中list集合的排序方法
  3. Android(安卓)NDK开发 Cmake环境调用 so文件
  4. 服务--Service
  5. 通过Android(安卓)Studio查看SDK源码
  6. Android学习笔记_32_通过WebView实现JS代码与Java代码互相通信
  7. Android_Button
  8. binder实例分析
  9. 最简单的android studio调用ffmpeg动态库

随机推荐

  1. windows下安装mysql8.0.18的教程(社区版)
  2. mysql完整性约束实例详解
  3. mysql中的sql_mode模式实例详解
  4. mysql外键的三种关系实例详解
  5. mybatis统计每条SQL的执行时间的方法示例
  6. windows7下mysql8.0.18部署安装教程图解
  7. mysql优化小技巧之去除重复项实现方法分
  8. mysql中null(IFNULL,COALESCE和NULLIF)相关
  9. 使用MySQL实现一个分布式锁
  10. mysql日期和时间的间隔计算实例分析