Activity之间传递参数

一、传递简单参数

firstActivity.java

Intent i=new Intent(firstActivity.this,secondActivity.class);

i.putExtra("data","hello Android");//这句用来给一个名称为data的字符串变量赋值“hello Android”,参数类型有很多种,可以自行选择

startActivity(i);

 

secondActivity.java​

Intent i =getIntent();

String data =i.getStringExtra("data");//通过和此Activity关联的Intent来获取字符串的值

 

二、传递数据包 Bundle

​firstActivity.java

Intent i=new Intent(firstActivity.this,secondActivity.class);

Bundle b =new Bundle();//Bundle中可以存储多种基础类型的数据,Bundle中也可以嵌套Bundle

b.putString("name","han meimei");

b.putInt("age",2);​

i.putExtras(b);​//i.putExtra("b",b);

startActivity(i);

 

secondActivity.java

​Intent i =getIntent();

Bundle data =i.getExtras();

String name =data.getString("name");

int age =data.getInt("age");

String name1 =data.getString("name1","li lei");//name1没有在firstActivity中赋值,可以在此指定一个默认值

 

三、传递值对象

传递一个自定义的数据类型

要想实现自定义的数据类型的传递,要对自定义对象进行序列化,有两种方法,实现Serializable(java 提供的序列化的接口),实现Parcelable(Android提供的实现序列化的接口)​

第一种方法​

public class User implements Serializable

{

      private String name;

      private int age;

}

 

firstActivity.java

​Intent i=new Intent(firstActivity.this,secondActivity.class);

i.putExtra("user",new User("han meimei",2));​

startActivity(i);

 

 

secondActivity.java

​Intent i =getIntent();

User user =(User)i.getserializableExtra("user");

 

第二种方法

要重载两个函数,因为没有全自动的进行序列化,要手动的进行序列化​

​public class User implements Parcelable

{

      private String name;

      private int age;

 

     @Override

     public int describeContents(){ return 0;}

     @Override//此函数系统会自动执行

     public void writeToParcel(Parcel dest,int flags)

     {

            dest.writeString(getName());

            dest.writeInt(getAge())​;

      }​

 

    public static final CreatorCREATOR =new Creator(){

             @Override

              public User createFromParcel(Parcel source)

              {

                   return new User(source.readString(),Source.readInt());

              }

              @Override

              public User[] newArray(int size)

              {

                      return new User[size];

             }​​

}

firstActivity.java

​Intent i=new Intent(firstActivity.this,secondActivity.class);

i.putExtra("user",new User("han meimei",2));​

startActivity(i);

secondActivity.java

​Intent i =getIntent();

User user =(User)i.getserializableExtra("user");

 

四、获取Activity的返回参数​

 

firstActivity.java

startActivityForResult(i,0);

@Override

protected void onActivityResult(int requestCode,int resultCode,Intent data)

{}//该函数可以获得请求码,返回码以及传递的数据​

 

secondActivity.java

    Intent i =new Intent();​

   i.putExtra("name","hha");​

    setResult(1,i);//返回状态码,可以自己指定数字代表的意思

​     finsh();//结束当前的Activity

posted @ 2016-03-27 14:59  艳鬼  阅读(175)  评论(0编辑  收藏  举报