Android开发实践 巧用Activity和Fragment

来源:互联网 发布:阿里云服务器空间清理 编辑:程序博客网 时间:2024/06/05 09:55

转载请注明出处:http://blog.csdn.net/smartbetter/article/details/51452313

1.Activity的生命周期

1)多个Activity组成Activity栈,当前活动位于栈顶。我们先来看看各种Activity基类的类图:

Activity基类的类图

当Activity类定义出来之后,这个Activity何时被实例化、它所包含的方法何时被调用,这些都不是由开发者所决定的,都应该由Android系统来决定。
下面我们来看一下Activity的生命周期:

Activity的生命周期

2.Activity的用法

1)启动、关闭Activity

// 首先需要创建启动的Activity对应的IntentIntent intent = new Intent(MainActivity.this, TwoActivity.class);// 启动ActivitystartActivity(Intent intent);startActivityForResult(Intent intent, int requestCode); // requestCode:请求码//startActivityForResult方法以指定的请求码启动Activity,并通过重写onActivityResult方法获取返回的结果。// 关闭Activityfinish();finishActivity(int requestCode);// finishActivity方法结束以startActivityForResult方法启动的Activity。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

2)启动其他Activity并返回结果

当前Activity重写onActivityResult(int requestCode, int resultCode, Intent intent)
requestCode:请求码(指出该方法是从哪个请求的结果触发的)
resultCode:Activity返回的结果码(指出返回的数据来自于哪个新的Activity)
被启动的Activity需要调用setResult()方法设置处理结果。

实例:
在当前Activity中重写onActivityResult方法

public class MainActivity extends Activity {    Button bn;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        // 获取界面上的组件        ...        // 绑定事件监听器        bn.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View view) {                Intent intent = new Intent(MainActivity.this, TwoActivity.class);                startActivityForResult(intent, 0); // 0是请求码,用于标识该请求            }        });    }    @Override    public void onActivityResult(int requestCode, int resultCode, Intent intent) {        // 处理特定的结果        if (requestCode == 0 && resultCode == 0) {            // 取出Intent里的Extras数据            Bundle data = intent.getExtras();            // 取出Bundle中的数据            String result = data.getString("test");            Toast.makeText(getApplicationContext(), result, 0).show();        }    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

然后在被启动的TwoActivity中调用setResult()方法设置处理结果

// 获取启动该Activity之前的Activity对应的IntentIntent intent = getIntent();intent.putExtra("test", "test");// 设置该SelectActivity的结果码,并设置结束之后退回的ActivitySelectCityActivity.this.setResult(0, intent);// 结束TwoActivityTwoActivity.this.finish();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

3.使用Bundle在Activity之间交换数据

Intent提供了多个重载的方法来“携带”额外的数据,如下:

intent.putExtras(Bundle data); // 向Intent放入数据包intent.putExtras(String name, Xxx value); // 向Intent中按key-value对的形式放入数据intent.getExtras(); // 取出Intent中携带的数据包intent.getXxxExtras(String name); //从Intent中按key取出指定类型的数据
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

上面方法中Bundle就是一个简单的数据携带包,Intent主要通过Bundle对象来携带数据,Bundle包含多个方法来存取数据:

Bundle bundle = new Bundle(); // 首先创建一个Bundle对象bundle.putXxx(String key, Xxx data); // 向Bundle中放入数据bundle.putSerializable(String key, Serializable data); // 向Bundle中放入一个可序列化的对象(即实现了java.io.Serializable接口)bundle.getXxx(String key); // 从Bundle中取出数据bundle.getSerializable(String key); // 从Bundle中取出一个可序列化的对象
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

4.Activity的四种加载模式

配置AndroidManifest.xml中Activity时,可指定android:launchMode属性用于配置该Activity的加载模式,该属性支持4个属性值:
standard:标准模式;
singleTop:栈顶单例模式;
singleTask:栈内单例模式(如果目标Activity已经存在、但没有位于栈顶,系统会把位于该Activity上面的所有Activity移出Task栈,从而使目标Activity转入栈顶);
singleInstance:全局单例模式(新创建Activity将放入新栈,一个栈只包含一个Activity,如果目标Activity已经存在,系统会把该Activity所在Task转到前台显示出来)。

5.Fragment的生命周期

Fragment是Android3.0引入的新API,Fragment代表Activity子模块(Activity片段),Fragment必须嵌入到Activity中使用,Fragment的生命周期受它所在Activity的生命周期的控制。

Fragment可调用getActivity()方法获取它所在Activity;
Activity可调用FragmentManager的findFragmentById()或findFragmentByTag()方法获取Fragment;
在Activity运行过程中,可调用FragmentManager的add()、remove()、replace()方法动态的添加、删除和替换Fragment。

1)我们先来看看各种Fragment基类的类图:

Fragment基类的类图

2)下面我们来看一下Fragment的生命周期,并和Activity的生命周期做对比:

Fragment的生命周期Fragment对比Activity

6.Fragment的用法

1)创建Fragment

创建Fragment通常要实现如下三个方法:
onCreate()、onCreateView()、onPause()
为了控制Fragment显示的组件,通常需要重写onCreateView()方法,该方法返回的View将作为该Fragment显示的View组件。

// 重写该方法,该方法返回的View将作为Fragment显示的组件@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {    // 加载/res/layout/目录下的fragment.xml布局文件    View view = inflater.inflate(R.layout.fragment, container, false);    TextView name = (TextView)view.findViewById(R.id.name));    ...    return view;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

2)将Fragment添加到Activity

将Fragment添加到Activity有如下两种方式:

第1种:在布局文件中使用<fragment.../>元素添加Fragment,<fragment.../>元素的android:name属性指定Fragment的实现类。第2种:在Java代码中通过FragmentTransaction对象的add()方法来添加Fragment。Activity的getFragmentManager()方法可返回FragmentManager,FragmentManager对象的beginTransaction()方法即可开启并返回FragmentTransaction对象。

3)如何在Activity中动态的添加、更新、以及删除Fragment呢?

首先需要在MainActivity布局文件中添加FrameLayout(设置id为fl),然后简单创建一个两个Fragment(MyFragment和TwoFragment)如下:

public class MyFragment extends Fragment   {      @Override      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {          return inflater.inflate(R.layout.fragment_my, container, false);      }  }  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
public class TwoFragment extends Fragment   {      @Override      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {          return inflater.inflate(R.layout.fragment_two, container, false);      }  }  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

接下来就可以在MainActivity中动态的添加、更新、以及删除Fragment了,MainActivity中调用的方法如下:

// 设置默认的FragmentFragmentManager fm = getFragmentManager();  FragmentTransaction transaction = fm.beginTransaction();  myFragment = new MyFragment();  transaction.replace(R.id.fl, myFragment);  transaction.commit();  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

假设点击某按钮更新Fragment,该按钮点击事件如下:

@Override  public void onClick(View v) {      FragmentManager fm = getFragmentManager();      // 开启Fragment事务      FragmentTransaction transaction = fm.beginTransaction();      twoFragment = new TwoFragment();      // 使用当前Fragment的布局替代fl的控件      transaction.replace(R.id.fl, twoFragment);      // transaction.addToBackStack();  // 将事物添加到back栈,允许用户按BACK按键返回到替换Fragment之前的状态    // 事务提交      transaction.commit();  }  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
0 0