首页 > 代码库 > Android 之数据传递小结
Android 之数据传递小结
Android开发中,在不同模块(如Activity)间经常会有各种各样的数据需要相互传递,常用的的有五种传递方式。它们各有利弊,有各自的应用场景。下面分别介绍一下:
1、 Intent对象传递简单数据
Intent的Extra部分可以存储传递的数据,可以传送int, long, char等一些基础类型。
[1]传递页面:
Intent intent = new Intent();intent.setClass(MainActivity.this, SecondActivity.class);Bundle bundle = new Bundle(); //打包发送bundle.putString("name","123"); //绑定参数intent.putExtra("maps",bundle);startActivity(intent);
[2]接收页面:
@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); Intent intent = this.getIntent(); Bundle bundle = intent.getBundleExtra("maps"); //获取打包数据bundle String name = bundle.getString("name"); //取出需要的数据 tv.setText(name); setContentView(tv);}或者@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second); TextView txt = (TextView)this.findViewById(R.id.txt); Intent intent = this.getIntent(); Bundle bundle = intent.getBundleExtra("maps"); //获取打包数据bundle String name = bundle.getString("name"); //取出需要的数据 txt.setText(name); }
2.、Intent对象传递复杂数据
有时候我们想传递如ArrayList之类复杂些的数据,这种原理是和上面一种是一样的,只是在传参数前,要用新增加一个List将对象包起来。如下:
Android 之数据传递小结
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。