【Android基础】页面跳转与传值(Activity跳转与传值)

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

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

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

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

Intent intent = new Intent(A.this, B.class); startActivity(intent);

也可以这样写:

Intent intent = new Intent(); intent.setClass(A.this, B.class); startActivity(intent);

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

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

如果数据比较少,比如只要传一个名字,那么只要j加一句"intent.putExtra("Name", "feng88724");"即可,代码如下:

Intent intent = new Intent(); intent.setClass(A.this, B.class); intent.putExtra("Name", "feng88724"); startActivity(intent); 

如果数据比较多,就需要使用 Bundle类了,代码如下: (说明直接看注释)

Intent intent = new Intent(A.this, B.class); /* 通过Bundle对象存储需要传递的数据 */ Bundle bundle = new Bundle(); /*字符、字符串、布尔、字节数组、浮点数等等,都可以传*/ bundle.putString("Name", "feng88724"); 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获取数据的代码:

@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"方法

@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页面上加一个返回按钮,并在事件写如下代码:

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

本讲就这么多。

转载于:https://www.cnblogs.com/feng88724/archive/2011/02/10/1961225.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值