Intent的用法(一),启动activity传递数据以及startActivityForResult .

Intent很神奇.可以用Intent来启动新的Activity,启动广播,启动服务,发送数据........太多了.

这里介绍下,使用Intent启动新的Activity,传递数据,以及startActivityForResult()方法的使用.


我们这里有两个Activity,MainActivity.java和OtherActivity.java. 我们需要做的是,点击Button的时候,获取到MainActivity中的用户输入的数据,传递给OtherActivity,在OtherActivity上进行整合后,在传递给MainActivity进行显示.

先看效果如,也就是整个流程:



第一步  从MainActivity跳转到OtherActivity,并将输入的数据传递过去.

代码如下:

  1. // 将Intent初始化 Intent(packageContext, cls)   
  2. // packageContext指的是当前Activity   
  3. // cls指的是目标Activity   
  4. intent = new Intent(MainActivity.this, OtherActivity.class);  
  5. // 创建Bundle对象用来存放数据,Bundle对象可以理解为数据的载体   
  6. Bundle b = new Bundle();  
  7. // 调用Bundle对象的putString方法,采用 key-value的形式保存数据   
  8. b.putString("name", name.getText().toString());  
  9. b.putString("age", age.getText().toString());  
  10. // 将数据载体BUndle对象放入Intent对象中.   
  11. intent.putExtras(b);  
  12. // 调用startActivityForResult方法   
  13. // startActivityForResult(intent,requestCode);   
  14. // intent,数据载体   
  15. // requestCode 请求的Code,这里一般 大于等于0的整型数据就可以.   
  16. startActivityForResult(intent, 1);  
			// 将Intent初始化 Intent(packageContext, cls)
			// packageContext指的是当前Activity
			// cls指的是目标Activity
			intent = new Intent(MainActivity.this, OtherActivity.class);
			// 创建Bundle对象用来存放数据,Bundle对象可以理解为数据的载体
			Bundle b = new Bundle();
			// 调用Bundle对象的putString方法,采用 key-value的形式保存数据
			b.putString("name", name.getText().toString());
			b.putString("age", age.getText().toString());
			// 将数据载体BUndle对象放入Intent对象中.
			intent.putExtras(b);
			// 调用startActivityForResult方法
			// startActivityForResult(intent,requestCode);
			// intent,数据载体
			// requestCode 请求的Code,这里一般 大于等于0的整型数据就可以.
			startActivityForResult(intent, 1);

注释已经比较详细了,这里值得一提的是,由于需要OtherActivity返回数据,所以采用了startActivityForResult()的方法,如果不需要返回数据,而是单纯的启动Activity,只需要使用tartActivity();就可以了.


第二步,OtherActivity接收数据,核心代码如下:

  1. // 获取数据   
  2. mIntent = getIntent();  
  3. Bundle b = mIntent.getExtras();  
  4. // 加载到tv   
  5. tv.setText("输入的姓名是:" + b.getString("name") + "输入的年龄是:"  
  6.         + b.getString("age"));  
		// 获取数据
		mIntent = getIntent();
		Bundle b = mIntent.getExtras();
		// 加载到tv
		tv.setText("输入的姓名是:" + b.getString("name") + "输入的年龄是:"
				+ b.getString("age"));
这里创建一个Bundle对象后,调用getString方法,根据先前设置的key而获取到数据.

第三步,返回数据,这一步可以分为两个部分:


       OtherActivity将需要返回的数据封装,代码如下:

      

  1. mIntent = new Intent(OtherActivity.this, MainActivity.class);  
  2. Bundle b = new Bundle();  
  3. b.putString("data", tv.getText().toString());  
  4. mIntent.putExtras(b);  
  5. this.setResult(RESULT_OK, mIntent);  
  6. OtherActivity.this.finish();  
			mIntent = new Intent(OtherActivity.this, MainActivity.class);
			Bundle b = new Bundle();
			b.putString("data", tv.getText().toString());
			mIntent.putExtras(b);
			this.setResult(RESULT_OK, mIntent);
			OtherActivity.this.finish();

      这里的setResult方法setResult(resultCode, data); resultCode,我们采用了系统提供的RESULT_OK,它的作用是用来识别Intent的.具体作用,在MainActivity的代码看完后,就明白了.还需要指出的是,setResult()之后,一定要调用当前Activity的finish()方法,如果不调用finish()方法,回报什么错呢?其实最好是亲自试一下.如果不finish(),点击"返回"按钮的时候,并没有执行跳转.这一点很重要.

     MainActivity需要进行的处理,接收到数据后,将数据显示在TextView中,代码如下:


      

  1. // 需要接收上一个Activity返回的数据,要重写Activity的 onActivityResult()方法.   
  2. @Override  
  3. protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  4.     // TODO Auto-generated method stub   
  5.     // 依据resultCode进行接收,这也是上个界面中需要设置resultCode的原因了   
  6.     switch (resultCode) {  
  7.     case RESULT_OK:  
  8.         // 这里写的比较省略,完整的写法应该是:   
  9.         // Bundle b = data.getExtras();   
  10.         // String show_string = b.getString("data");   
  11.         // show.setText(show_string);   
  12.         show.setText(data.getExtras().getString("data"));  
  13.         break;  
  14.   
  15.     default:  
  16.         break;  
  17.     }  
  18.     super.onActivityResult(requestCode, resultCode, data);  
  19. }  
	// 需要接收上一个Activity返回的数据,要重写Activity的 onActivityResult()方法.
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		// 依据resultCode进行接收,这也是上个界面中需要设置resultCode的原因了
		switch (resultCode) {
		case RESULT_OK:
			// 这里写的比较省略,完整的写法应该是:
			// Bundle b = data.getExtras();
			// String show_string = b.getString("data");
			// show.setText(show_string);
			show.setText(data.getExtras().getString("data"));
			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

以上是各个模块的核心代码.

接下来贴出来所有文件的源码.

两个xml文件:

mian.xml

  

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="@string/hello" />  
  11.   
  12.     <EditText  
  13.         android:id="@+id/name"  
  14.         android:layout_width="match_parent"  
  15.         android:layout_height="wrap_content"  
  16.         android:text="输入姓名" >  
  17.   
  18.         <requestFocus />  
  19.     </EditText>  
  20.   
  21.     <EditText  
  22.         android:id="@+id/age"  
  23.         android:layout_width="match_parent"  
  24.         android:layout_height="wrap_content"  
  25.         android:text="输入年龄" />  
  26.   
  27.     <Button  
  28.         android:id="@+id/button1"  
  29.         android:layout_width="wrap_content"  
  30.         android:layout_height="wrap_content"  
  31.         android:text="启动Intent,传递数据,接收数据" />  
  32.   
  33.     <TextView  
  34.         android:id="@+id/show"  
  35.         android:layout_width="wrap_content"  
  36.         android:layout_height="wrap_content"  
  37.         android:text="显示整合好的数据"  
  38.         android:textAppearance="?android:attr/textAppearanceLarge" />  
  39.   
  40. </LinearLayout>  
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="输入姓名" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="输入年龄" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="启动Intent,传递数据,接收数据" />

    <TextView
        android:id="@+id/show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="显示整合好的数据"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

other.xml

  

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:id="@+id/linearLayout1"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:id="@+id/textView1"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="Large Text"  
  12.         android:textAppearance="?android:attr/textAppearanceLarge" />  
  13.   
  14.     <Button  
  15.         android:id="@+id/button1"  
  16.         android:layout_width="wrap_content"  
  17.         android:layout_height="wrap_content"  
  18.         android:text="返回" />  
  19.   
  20. </LinearLayout>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="返回" />

</LinearLayout>

两个Activity的文件:

MainActivity.java


  1. package com.yongchun.intent.ui;  
  2.   
  3. /* 
  4.  *     public Bundle() { 
  5.  *       mMap = new HashMap<String, Object>(); 
  6.  *      mClassLoader = getClass().getClassLoader(); 
  7.  *      } 
  8.  *      Bundle的构造方法中,初始化了一个Map,实际上Bundle就是Map的进一步的封装, 
  9.  *      Bundle实际上采用的就是Map来保存数据 
  10.  *       
  11.  *   #####################################################    
  12.  *       
  13.  *     public Intent putExtra(String name, boolean value) { 
  14.  *          if (mExtras == null) { 
  15.  *             mExtras = new Bundle(); 
  16.  *        } 
  17.  *       mExtras.putBoolean(name, value); 
  18.  *      return this; 
  19.  *     } 
  20.  *      
  21.  *     Intent的putExtra方法中,实际上也是创建了一个Bundle对象. 
  22.  *     两种方式是一样的,换汤不换药. 
  23.  * */  
  24. import java.util.HashMap;  
  25.   
  26. import android.app.Activity;  
  27. import android.content.Context;  
  28. import android.content.Intent;  
  29. import android.os.Bundle;  
  30. import android.text.style.UpdateLayout;  
  31. import android.util.Log;  
  32. import android.view.View;  
  33. import android.view.View.OnClickListener;  
  34. import android.widget.Button;  
  35. import android.widget.EditText;  
  36. import android.widget.TextView;  
  37.   
  38. public class MainActivity extends Activity implements OnClickListener {  
  39.     /** Called when the activity is first created. */  
  40.   
  41.     private Button startButton;  
  42.     private EditText name, age;  
  43.     private TextView show;  
  44.     private Intent intent;  
  45.   
  46.     @Override  
  47.     public void onCreate(Bundle savedInstanceState) {  
  48.         super.onCreate(savedInstanceState);  
  49.         setContentView(R.layout.main);  
  50.         // 获取引用   
  51.         startButton = (Button) findViewById(R.id.button1);  
  52.         startButton.setOnClickListener(this);  
  53.         name = (EditText) findViewById(R.id.name);  
  54.         age = (EditText) findViewById(R.id.age);  
  55.         show = (TextView) findViewById(R.id.show);  
  56.   
  57.     }  
  58.   
  59.     public void onClick(View v) {  
  60.         // TODO Auto-generated method stub   
  61.         switch (v.getId()) {  
  62.         case R.id.button1:  
  63.   
  64.             // 将Intent初始化 Intent(packageContext, cls)   
  65.             // packageContext指的是当前Activity   
  66.             // cls指的是目标Activity   
  67.             intent = new Intent(MainActivity.this, OtherActivity.class);  
  68.             // 创建Bundle对象用来存放数据,Bundle对象可以理解为数据的载体   
  69.             Bundle b = new Bundle();  
  70.             // 调用Bundle对象的putString方法,采用 key-value的形式保存数据   
  71.             b.putString("name", name.getText().toString());  
  72.             b.putString("age", age.getText().toString());  
  73.             // 将数据载体BUndle对象放入Intent对象中.   
  74.             intent.putExtras(b);  
  75.             // 调用startActivityForResult方法   
  76.             // startActivityForResult(intent,requestCode);   
  77.             // intent,数据载体   
  78.             // requestCode 请求的Code,这里一般 大于等于0的整型数据就可以.   
  79.             startActivityForResult(intent, 1);  
  80.   
  81.             break;  
  82.   
  83.         default:  
  84.             break;  
  85.         }  
  86.   
  87.     }  
  88.   
  89.     // 需要接收上一个Activity返回的数据,要重写Activity的 onActivityResult()方法.   
  90.     @Override  
  91.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  92.         // TODO Auto-generated method stub   
  93.         // 依据resultCode进行接收,这也是上个界面中需要设置resultCode的原因了   
  94.         switch (resultCode) {  
  95.         case RESULT_OK:  
  96.             // 这里写的比较省略,完整的写法应该是:   
  97.             // Bundle b = data.getExtras();   
  98.             // String show_string = b.getString("data");   
  99.             // show.setText(show_string);   
  100.             show.setText(data.getExtras().getString("data"));  
  101.             break;  
  102.   
  103.         default:  
  104.             break;  
  105.         }  
  106.         super.onActivityResult(requestCode, resultCode, data);  
  107.     }  
  108.   
  109. }  
package com.yongchun.intent.ui;

/*
 *     public Bundle() {
 *       mMap = new HashMap<String, Object>();
 *      mClassLoader = getClass().getClassLoader();
 *      }
 *      Bundle的构造方法中,初始化了一个Map,实际上Bundle就是Map的进一步的封装,
 *      Bundle实际上采用的就是Map来保存数据
 *      
 *   #####################################################   
 *      
 *     public Intent putExtra(String name, boolean value) {
 *          if (mExtras == null) {
 *             mExtras = new Bundle();
 *        }
 *       mExtras.putBoolean(name, value);
 *      return this;
 *     }
 *     
 *     Intent的putExtra方法中,实际上也是创建了一个Bundle对象.
 *     两种方式是一样的,换汤不换药.
 * */
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.style.UpdateLayout;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {
	/** Called when the activity is first created. */

	private Button startButton;
	private EditText name, age;
	private TextView show;
	private Intent intent;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// 获取引用
		startButton = (Button) findViewById(R.id.button1);
		startButton.setOnClickListener(this);
		name = (EditText) findViewById(R.id.name);
		age = (EditText) findViewById(R.id.age);
		show = (TextView) findViewById(R.id.show);

	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.button1:

			// 将Intent初始化 Intent(packageContext, cls)
			// packageContext指的是当前Activity
			// cls指的是目标Activity
			intent = new Intent(MainActivity.this, OtherActivity.class);
			// 创建Bundle对象用来存放数据,Bundle对象可以理解为数据的载体
			Bundle b = new Bundle();
			// 调用Bundle对象的putString方法,采用 key-value的形式保存数据
			b.putString("name", name.getText().toString());
			b.putString("age", age.getText().toString());
			// 将数据载体BUndle对象放入Intent对象中.
			intent.putExtras(b);
			// 调用startActivityForResult方法
			// startActivityForResult(intent,requestCode);
			// intent,数据载体
			// requestCode 请求的Code,这里一般 大于等于0的整型数据就可以.
			startActivityForResult(intent, 1);

			break;

		default:
			break;
		}

	}

	// 需要接收上一个Activity返回的数据,要重写Activity的 onActivityResult()方法.
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		// 依据resultCode进行接收,这也是上个界面中需要设置resultCode的原因了
		switch (resultCode) {
		case RESULT_OK:
			// 这里写的比较省略,完整的写法应该是:
			// Bundle b = data.getExtras();
			// String show_string = b.getString("data");
			// show.setText(show_string);
			show.setText(data.getExtras().getString("data"));
			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

}

OtherActivity.java


  1. package com.yongchun.intent.ui;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Intent;  
  5. import android.os.Bundle;  
  6. import android.util.Log;  
  7. import android.view.View;  
  8. import android.view.View.OnClickListener;  
  9. import android.widget.Button;  
  10. import android.widget.TextView;  
  11.   
  12. public class OtherActivity extends Activity implements OnClickListener {  
  13.   
  14.     private TextView tv;  
  15.     private Button OK;  
  16.     private Intent mIntent;  
  17.   
  18.     @Override  
  19.     protected void onCreate(Bundle savedInstanceState) {  
  20.         // TODO Auto-generated method stub   
  21.         super.onCreate(savedInstanceState);  
  22.         setContentView(R.layout.other);  
  23.   
  24.         // 获取引用   
  25.         tv = (TextView) findViewById(R.id.textView1);  
  26.         OK = (Button) findViewById(R.id.button1);  
  27.         OK.setOnClickListener(this);  
  28.         // 获取数据   
  29.         mIntent = getIntent();  
  30.         Bundle b = mIntent.getExtras();  
  31.         // 加载到tv   
  32.         tv.setText("输入的姓名是:" + b.getString("name") + "输入的年龄是:"  
  33.                 + b.getString("age"));  
  34.     }  
  35.   
  36.     public void onClick(View v) {  
  37.         // TODO Auto-generated method stub   
  38.         switch (v.getId()) {  
  39.         case R.id.button1:  
  40.             mIntent = new Intent(OtherActivity.this, MainActivity.class);  
  41.             Bundle b = new Bundle();  
  42.             b.putString("data", tv.getText().toString());  
  43.             mIntent.putExtras(b);  
  44.             this.setResult(RESULT_OK, mIntent);  
  45.             OtherActivity.this.finish();  
  46.             break;  
  47.   
  48.         default:  
  49.             break;  
  50.         }  
  51.   
  52.     }  
  53.   
  54. }  
package com.yongchun.intent.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

/**
 * 作者:肥鱼 QQ群:104780991 Email:zhaoyongchun2011@gmail.com
 * 关于:一条致力于Android开源事业的鱼,还是肥的.吃得多赚的少还不会暖床,求包养.
 */
public class OtherActivity extends Activity implements OnClickListener {

	private TextView tv;
	private Button OK;
	private Intent mIntent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.other);

		// 获取引用
		tv = (TextView) findViewById(R.id.textView1);
		OK = (Button) findViewById(R.id.button1);
		OK.setOnClickListener(this);
		// 获取数据
		mIntent = getIntent();
		Bundle b = mIntent.getExtras();
		// 加载到tv
		tv.setText("输入的姓名是:" + b.getString("name") + "输入的年龄是:"
				+ b.getString("age"));
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.button1:
			mIntent = new Intent(OtherActivity.this, MainActivity.class);
			Bundle b = new Bundle();
			b.putString("data", tv.getText().toString());
			mIntent.putExtras(b);
			this.setResult(RESULT_OK, mIntent);
			OtherActivity.this.finish();
			break;

		default:
			break;
		}

	}

}

在MainActivity.java的开头处有一大段注释,说的是Bundle保存数据的机制以及使用Intent对象的putString方法保存数据的机制.Bundle实际上就是对Map的进一步的封装.而是用Intent对象的putString方法时,实际上还是创建了一个Bundle对象.我们来看一下Bundle类中的构造函数:

  1. public Bundle() {  
  2.     mMap = new HashMap<String, Object>();  
  3.     mClassLoader = getClass().getClassLoader();  
  4. }  
    public Bundle() {
        mMap = new HashMap<String, Object>();
        mClassLoader = getClass().getClassLoader();
    }

很明显,实际上就是初始化了HashMap.

我们再看一下Intent类中某个putExtra()的方法.

  1. public Intent putExtra(String name, char value) {  
  2.     if (mExtras == null) {  
  3.         mExtras = new Bundle();  
  4.     }  
  5.     mExtras.putChar(name, value);  
  6.     return this;  
  7. }  
    public Intent putExtra(String name, char value) {
        if (mExtras == null) {
            mExtras = new Bundle();
        }
        mExtras.putChar(name, value);
        return this;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值