1. 要点
这里介绍如何用Intent和startActivity()启动一个新的Activity,即打开另外一个UI。这里先介绍的是一个application内部的各个Activity之间的调用。
2. 示例功能
这里有两个Activity,一个称为Caller,另外一个称为Callee。名称取自手机呼叫中的主叫和被叫之意。各包括一个简单的Button控件,在Caller中,点了按钮之后,就通过startActivity()调用Callee;在Callee中点了按钮之后,就结束自己,回到Caller。
3. 代码
主要代码包括两个地方。
CallerActivity中点击按钮的事件处理:
Button startNewActivity = (Button) this.findViewById(R.id.start_new_activity);
startNewActivity.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
LogUtils.d(TAG, "onClick()");
Intent intent = new Intent();
intent.setClass(CallerActivity.this, CalleeActivity.class);
intent.putExtra("hello", "Hello, Callee!");
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
});
Callee处理完了自己的事务之后,需要返回CallerActivity。这里简化为点击按钮,代码为:
Button finish = (Button) this.findViewById(R.id.finish);
finish.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ToastUtils.showShort(CalleeActivity.this, "I will be finished.");
LogUtils.d(TAG, "onClick()");
finish();
}
});
4. Intent和startActivity()
Intent用于在各个Activity之间传递信息,startActivity()用于启动指定的Activity。
Intent intent = new Intent();
intent.setClass(CallerActivity.this, CalleeActivity.class);
intent.putExtra("hello", "Hello, Callee!");
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
这里用了最简单一种调用方式,直接在Intent中指定了目标Activity的名称。
后面会再描述intent filter的传递方式,可以在不同的应用之间进行通信。
5. 示例源码下载
http://download.csdn.net/detail/u013344915/8789997
6. 编译问题
如果Import到ADT中编译有问题,可以检查project.properties文件的内容:
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your
# project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target.
target=android-19
android.library.reference.1=../appcompat_v7_5
最后一行根据当前ADT环境中的appcompat_v7_ n的情况做适当修改即可。这一行表示所依赖的project名称,如果在当前ADT环境中找不到就会编译出错。
关于appcompat_v7,请参考http://www.cnblogs.com/peach/p/4112207.html。