

首先用ADT生成一个框架程序,其中包含intentdemo.java程序,有layout.main.xml资源,有values.strings.xml,有androidmanifest.xml:
package com.sw.test;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class IntentDemo extends Activity {
/** Called when the activity is first created. */
private void msgbox(String Message) {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("This is Title");
alertDialog.setMessage(Message);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
}
});
alertDialog.show();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button firstbtn = (Button) findViewById(R.id.firstbtn);
// Button firstbtnservice = (Button) findViewById(R.id.firstbtnservice);
// Button secondbtn = (Button) findViewById(R.id.secondbtn);
// Button secondbtnservice = (Button)
// findViewById(R.id.secondbtnservice);
firstbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// 显式启动FirstIntentDemo Activity
Intent i = new Intent(getApplicationContext(),FirstIntentDemo.class);
startActivity(i);
// msgbox("测试");
}
});
}
}
为创建按钮firstbtn,需在main.xml中增加按钮,选择form widgets中的按钮,拖入右边黑窗口。注意界面上各种属性,并且在按钮上点击右键有更多设置。可点右键将按钮ID设为”firstbtn”,这样即可对应R.id.firstbtn。
然后需制作下一级activity,可在包目录上点新建类,类名处输入,而在父类处输入android.app.Activity,这样import语句会自动正确生成。然后就是在类中加入:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstintent);
}
加入方法有技巧,在左侧类结构列表中点右键,在Source下,有Override/impl..选项,可直接选出OnCreate方法,甚至里面代码框架都提供出来了。
由于有R.layout.firstintent,需在layout下创建firstintent.xml文件,可从main.xml拷贝得来。再加以修改。如删去main.xml中的按钮等。亦可选择New ,从中选择android xml,从中选择layout类型的xml,很方便。
运行时,出现异常关闭,想想原来此activity还未在AndroidManifest.xml中定义。点击下面application栏,出现界面,点击Add,双击Activity添加,还未改名吗?可在右侧选择,由于firstintentdemo类已有,可直接选择,下面可选择一字符串资源,以作为此activity的名字显示。
此时编译,即可在模拟器中正常运行。如例子代码所示,此为intent显示调用,未设置intent-filter以用于隐式调用。
原创文章,作者:苏葳,如需转载,请注明出处:https://www.swmemo.com/282.html
