Intent学习(2)

来源:互联网 发布:java分支语句例子 编辑:程序博客网 时间:2024/06/06 02:44

一、Intent传递数据


1.传递常用类型数据

A.传递数据

Intent提供了一系列的putExtra()方法的重载

 Intent intent = new Intent( FirstActivity.this , SecondActivity. class );

intent.putExtra("stringValue","value");  //key value的形式,第一个参数为键,第二个为值

intent.putExtra("intValue",1);//传递int值

B.接收数据

Intent intent =getIntent();

String value=intent.getStringExtra("stringValue");//接收String值

int intValue=intent.getIntExtra("intValue");//接收int值

以此类推,使用getXXXExtra 方法,接收不同类型的值

2.传递数组

A.传递数据
<pre style="font-family: 宋体; font-size: 14.3pt; background-color: rgb(255, 255, 255);"><pre name="code" class="java"><span style="white-space:pre"></span>    Intent intent=new Intent(MainActivity.this,ImagePagerActivity.class);                    ArrayList intList=new ArrayList();                    intList.add(2);                    intList.add(4);                    intList.add(6);                    intent.putIntegerArrayListExtra("intList",intList);                    ArrayList stringList=new ArrayList();                    stringList.add("x");                    stringList.add("y");                    stringList.add("z");                    intent.putStringArrayListExtra("stringList",stringList);


B.接收数据
<pre style="font-family: 宋体; font-size: 14.3pt; background-color: rgb(255, 255, 255);"><pre style="font-family: 宋体; font-size: 14.3pt; background-color: rgb(255, 255, 255);"><span style="background-color:#e4e4ff;"></span><pre name="code" class="java"><span style="white-space:pre"></span>ArrayList stringList=getIntent().getStringArrayListExtra("stringList");        ArrayList intList=getIntent().getIntegerArrayListExtra("intList");

接收数据 

2.Bundle传递数据

Bundle类是一个key-value,A mapping from String values to various Parcelable types.
A.使用示例:
<span style="color:#333333;">    传递bundle数据   Bundle bundle=new Bundle();                    bundle.putString("bundleString","String");                    bundle.putInt("bundleInt",1);                    intent.</span><span style="color:#ff0000;">putExtras</span><span style="color:#333333;">(bundle); // <span style="color: rgb(255, 0, 0); font-family: "microsoft yahei";font-size:14px; font-weight: 600; line-height: 29.7px; white-space: pre-wrap; background-color: rgb(240, 240, 240);">putExtras  </span></span><span style="color: rgb(51, 51, 51); font-size: 19.0667px; font-family: "microsoft yahei"; white-space: pre-wrap;">有s</span>

接收数据<span style="white-space:pre"></span>Bundle bundle = getIntent().getExtras();        <span style="white-space:pre"></span>System.out.println(bundle.getString("bundleString"));        <span style="white-space:pre"></span>System.out.println(bundle.getInt("bundleInt"));        <span style="white-space:pre"></span>System.out.println(bundle.getInt("xxxxx",10086));
<span style="white-space:pre"></span>//此方法的意思是如果没有传值,就设置一个默认值

B.为啥要使用bundle呢?
如果我现在有Activity A ,B ,C ;  现在我要把值通过A经过B传给C
如果我在A中用了 Bundle 的话  我把Bundle传给B 在B中再转传到C  C就可以直接去了 ,而且可以在B中处理相关的值,再传递下去


0 0