【Android开发】启动另一个Activity

通过前面的学习,知道如何在一个Activity中加入一个文本框和一个按钮,现在来学习如何在MainActivity中启动另一个新的Activity。


一、响应按钮的点击

为了响应按钮(button)的点击事件, 打开activity_main.xml布局文件,加入android:onClick属性到<Button>元素中。如下:

<Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_send" 
        android:onClick="sendMessage" />

其中android:onClick属性值"sendMessage",是activity中的方法名,当用户点击该按钮时,系统调用该方法。

打开MainActivity类(在工程目录src/中),加入相应的方法sendMessage(),如下:

/* Called when the user clicks the Send Button */
    public void sendMessage(View view){
    	// Do something in response to button
    }

这需要导入View类:

import android.view.View;
技巧:在Eclipse中,按Ctrl+Shift+O来导入缺失的类

为了使系统匹配源代码中的方法语android:onClick中给定的方法一致,署名(signature)必须明确的显示出来,确切的说,方法必须是:

  • 是public
  • 有一个void的返回值
  • 有一个View作为唯一的参数(这个参数将是点击的View)
接下来,完成sendMessage的功能,即读取文本框中的内容,然后传输文本内容到另一个activity中。

二、构建一个Intent
Intent是一个对象,用来在运行时间绑定各个组件(像两个activities)。Intent表示一个App"打算做某事",Intent可以用于广泛的各种任务,不过大多数情况下,用于启动另一个activity。

在sendMessage()方法中,创建一个Intent来启动一个称为DisplayMessageActivity的Activity。
Intent intent = new Intent(this, DisplayMessageActivity.class);
此处使用的构造器有两个参数:
  • Context作为其第一个参数(此处用this,因为Activity类是Context的子类)
  • App组件的类,系统将传递Intent到该类
一个Intent不仅允许启动另一个activity,而且可以搬运大量的数据到另一个activity中,在sendMessage()方法中,使用findViewById()来获取EditText元素,然后加入文本值到Intent中,如下:
/* Called when the user clicks the Send Button */
    public void sendMessage(View view){
    	// Do something in response to button
    	Intent intent = new Intent(this, DisplayMessageActivity.class);
    	EditText editText = (EditText)findViewById(R.id.edit_message);
    	String message = editText.getText().toString();
    	intent.putExtra(EXTRA_MESSAGE, message);
    }
注:需要导入android.content.intent和android:widget.EditText。同时需要定义常量EXTRA_MESSAGE,如下:
public class MainActivity extends Activity {

    public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
    ...
}
一个Intent可以携带各种数据类型的键-值(key-value)对(称为extra)的集合。
putExtra()方法使用键名作为第一个参数,然后值(value)在第二个参数中。

为了让下一个activity查询extra数据,应该使用public constant 为intent的extra定义一个键。所以在MainActivity类的顶部加入了EXTRA_MESSAGE的定义。

通常在实践中,使用App的包名作为前缀为intent的extra定义keys比较好。这样,当自己的App与其他的App交互时,确保其值是唯一的。

三、开启第二个Activity
为了开启一个activity。需要调用startActivity(),同时传递定义的Intent给它。当系统收到该调用时,启动Intent指定的Activity实例。
完整的sendMessage()方法的代码如下:
/* Called when the user clicks the Send Button */
    public void sendMessage(View view){
    	// Do something in response to button
    	Intent intent = new Intent(this, DisplayMessageActivity.class);
    	EditText editText = (EditText)findViewById(R.id.edit_message);
    	String message = editText.getText().toString();
    	intent.putExtra(EXTRA_MESSAGE, message);
    	startActivity(intent);
    }
现在需要创建一个DisplayMessageActivity类。

四、创建第二个acitivity

利用Eclipse创建一个新的Activity
1.点击工具栏的New按钮,在出现的窗口中,打开Android文件夹,选择Android Activity,然后点击Next。
2.选择BlackActivity,点击Next。
3.填写Activity的细节。
  • Project:MyFirstApp
  • Activity Name:DisplayMessageActivity
  • LayoutName:activity_display_message
  • Title:My Message
  • Hierarchial Parent:com.example.myfirstapp.MainActivity
  • Navigation Type:None
4.点击完成

DisplayMessageActivity类现在看起来应该如下:
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.os.Build;

public class DisplayMessageActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_display_message);
		// Show the Up button in the action bar.
		setupActionBar();
	}

	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.display_message, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			//  http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}

所有的Activity子类必须实现onCreate()方法,当创建一个新的Activity实例时系统将会调用它。该方法所在的地方同时必须使用setContentView()方法来定义activity布局,同时该方法所在的地方也是activity组件执行初始化建立的地方。

把创建的activity加入到manifest。
所有的activities必须在manifest文件AndroidManifest.xml中使用<activity>元素声明,如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=" http://schemas.android.com/apk/res/android"
    package="com.example.myfirstapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.myfirstapp.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.myfirstapp.DisplayMessageActivity"
            android:label="@string/title_activity_display_message"
            android:parentActivityName="com.example.myfirstapp.MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.myfirstapp.MainActivity" />
        </activity>
    </application>

</manifest>
其中android:parentActivityName属性声明了在App逻辑层次中Activity的父Activity的名字。系统使用该值来执行缺省的导航行为,如Android 4.1中的up导航。

五、接收Intent和显示信息
每个Activity通过Intent被调用,不管用户如何操纵,需要通过调用getIntent()来获取Intent以启动activity,以及检索Intent中包含的数据。
在DisplayMessageActivity类的onCreate()方法中,获取Intent,然后提取MainActivity传送过来的信息。

为了在屏幕上显示信息,创建一个TextView,使用setText()方法进行本文设置,然后把它作为activity布局的根view,传递给setContentView()方法。
DisplayMessageActivity类的完整的onCreate()的代码如下:
protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// Get the message from the intent
		Intent intent = getIntent();
		String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
		
		// Create the text view
		TextView textView = new TextView(this);
		textView.setTextSize(40);
		textView.setText(message);
		
//		setContentView(R.layout.activity_display_message);
		setContentView(textView);
		
		// Show the Up button in the action bar.
		setupActionBar();	
		
	}

六、运行结果



评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值