一个Android应用程序很少会只有一个Activity对象,如何在多个Activity之间进行跳转,而且能够互相传值是一个很基本的要求。

本次我们就简短的说一下,Android中页面跳转以及传值的几种方式!

Activity跳转与传值,主要是通过Intent类来连接多个Activity,通过Bundle类来传递数据。

最常见最一般的页面跳转代码,很简单,如下:

view plaincopy to clipboardprint?
 Intent intent = new Intent(A.this, B.class);  
 startActivity(intent);


 

另外一种方法:

view plaincopy to clipboardprint?
 Intent intent = new Intent();  
 intent.setClass(A.this, B.class);  
 startActivity(intent);


 

只要这两句,就可以实现从A页面跳转到B页面了 (A、B均继承自Activity)。

有的时候,在跳转页面时还需要传递数据,这个时候如何做呢?

如果数据量少,比如只要传一个参数,那么只要加一句" intent.putExtra("Name", "testuser"); "即可,

功能代码如下:

view plaincopy to clipboardprint?
 Intent intent = new Intent();  
 intent.setClass(A.this, B.class);  
 intent.putExtra("Name", "testuser");  
 startActivity(intent);


 

如果数据量多,就需要使用 Bundle类了,

代码如下: (说明看注释)

view plaincopy to clipboardprint?
 Intent intent = new Intent(A.this, B.class);  
   
 /* Bundle对象存储需要传递的数据 */  
 Bundle bundle = new Bundle();   /*字符、字符串、布尔、字节数组、浮点数等等数据类型都可以传递*/  
 bundle.putString("Name", "testuser");  
 bundle.putBoolean("Ismale", true);  
   
 /*把bundle对象assign给Intent*/  
 intent.putExtras(bundle);    
 startActivity(intent);


 

以上我们讲的都是如何进行页面跳转及数据传递,那么在另一个页面B上,应该如何接收数据呢?

在A页面上是以Bundle封装了对象,自然在B页面也是以Bundle的方式来解开封装的数据。

主要通过"getIntent().getExtras()"方法来获取Bundle,然后再从Bundle中获取数据。

也可以通过" this.getIntent().getStringExtra("Name");"方法直接从Intent中获取数据。

从Bundle获取数据的代码:

view plaincopy to clipboardprint?

@Override  
  public void onCreate(Bundle savedInstanceState) {  
         super.onCreate(savedInstanceState);  
         /*加载页面*/  
         setContentView(R.layout.main);  
           
         /*获取Intent中的Bundle对象*/  
         Bundle bundle = this.getIntent().getExtras();  
           
         /*获取Bundle中的数据,注意类型和key*/  
         String name = bundle.getString("Name");  
         boolean ismale = bundle.getBoolean("Ismale");  
           
 }


 

有时,在页面跳转之后,需要返回到之前的页面,同时要保留用户之前输入的信息,这个时候该怎么办呢?

在页面跳转后,前一个Activity已经被destroy了。

如果要返回并显示数据,就必须将前一个Activity再次唤醒,同时调用某个方法来获取并显示数据。

要实现这个效果,需要做以下几步:

1. 首先,从A页面跳转到B页面时,不可以使用"startActivity()"方法,而要使用"startActivityForResult"方法。

2. 在A页面的Activity中,需要重写"onActivityResult"方法

view plaincopy to clipboardprint?
 @Override  
 protected void onActivityResult(int requestCode,int resultCode,Intent data){  
       
     switch(requestCode){  
     case RESULT_OK:  
         /*取得来自B页面的数据,并显示到画面*/  
         Bundle bundle = data.getExtras();  
           
         /*获取Bundle中的数据,注意类型和key*/  
         String name = bundle.getString("Name");  
         boolean ismale = bundle.getBoolean("Ismale");  
     }  
 }


 

3. 在B页面上加一个返回按钮,并在事件写如下代码:

view plaincopy to clipboardprint?
 /*给上一个Activity返回结果*/  
 B.this.setResult(RESULT_OK,intent);   /*结束本Activity*/  
 B.this.finish();