新建一个Activity有两种方式,一种是手动的去添加,手动的添加能让我们更好的了解Android的开发机制,一般新建一个Activity有几个步骤:
一.新建一个与Activity相挂钩的Layout布局文件
二.新建一个Activity类,并通过setContentView()函数为Activity类绑定Layout布局文件
三.在AndroidManifest.xml中注册Activity
四.在AndroidManifest.xml中通过 <intent-filter>标签把Activity设置为第一个启动的Activity
五.利用Intent对象设置Activity,并通过startActivity()函数启动Activity
六.通过Intent的putExtra()函数在不同的Activity中进行数据传输
- 新建Layout布局文件
<RelativeLayout 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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.helloword.HellowordActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
- 添加Activity类
package com.example.helloword;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class HellowordActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_helloword);//设置Layout文件
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.helloword, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
- 注册Activity类,并设置第一启动
<activity
android:name=".HellowordActivity"
android:label="@string/title_activity_helloword" >
///以下标签是设置第一启动/
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
- 启动Activity
Intent newIntent = new Intent();//新建一个Intent对象
//选择当前Activity和下一个要运行的Activity
newIntent.setClass(MainActivity.this, SecondActivity.class);
newIntent.putExtra("com.examples.helicopter.age", 20);//传递数据
newIntent.putExtra("com.examples.helicopter.name", "12345678");//传递数据
startActivity(newIntent);//启动Intent对象
手工添加只是为了更好的理解Android的机制,如已经熟悉机制的朋友可以通过右键直接建立新的Activity,编译器会根据你的设置自动帮你写入上面的代码。