在两个Activity之间传递值。这里使用的是 startActivityForResult(i,0) 这个函数。
具体的流程如下:
· · 在MainActivity.java中:
public class MainActivity extends ActionBarActivity { private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView=(TextView)findViewById(R.id.textView); findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(MainActivity.this, MainActivity2Activity.class); i.putExtra("user", new User("jikexuanyuan",2)); startActivityForResult(i,0); } } ); }
调用了startActivityForResult 之后应该再覆写
protected void onActivityResult(int requestCode,int resultCode,Intent data){ super.onActivityResult(requestCode,resultCode,data); textView.setText("from another acitivity de data is "+data.getStringExtra("data")); }界面如下:在MainActivity2Activity中,
public class MainActivity2Activity extends ActionBarActivity { private TextView tv; private EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_activity2); tv=(TextView)findViewById(R.id.textView2); editText=(EditText)findViewById(R.id.editText); Intent i=getIntent(); User user=(User)i.getParcelableExtra("user"); tv.setText(String.format("User info(name=%s,age=%d)",user.getName(),user.getAge())); findViewById(R.id.button2).setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { Intent i=new Intent(); i.putExtra("data",editText.getText().toString()); setResult(1,i); finish(); //用finish()才可以返回。 } } ); } }MainActivity2Activity 的界面如下:其中User这个对象,在User.java中构造:package com.example.administrator.myapplication; import android.os.Parcel; import android.os.Parcelable; import java.io.Serializable; /** * Created by Administrator on 15-5-25. */ public class User implements Parcelable{ private String name; private int age; public int getAge(){ return age; } public void setAge(int age){ this.age=age; } public String getName(){ return name; } public void setName(String name){ this.name=name; } public User(String name,int age){ this.name=name; this.age=age; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(getName()); dest.writeInt(getAge()); } public static final Creator<User> CREATOR=new Creator<User>(){ public User createFromParcel(Parcel source){ return new User(source.readString(),source.readInt()); } public User[] newArray(int size){ return new User[size]; } }; }中有1界面 讲值传送到2界面用到了 Parcelable的序列化。http://www.cnblogs.com/linjiqin/archive/2011/06/03/2071956.htmlstartActivityForResult用法详解: