页面跳转并传递数据

Android里面采用Intent类实现页面跳转,并且传递数据

 

Intent intent = new Intent();   
intent.setClass(activity1.this, activity2.class);   //描述起点和目标   
Bundle bundle = new Bundle();                           //创建Bundle对象   
bundle.putString("something", "Activity1发来的数据");     //装入数据   
intent.putExtras(bundle);                                //把Bundle塞入Intent里面   
startActivity(intent);                                     //开始切换 

 

Bundle是类似于Map的一种数据结构,通过key-value的形式存储数据

从跳转后的页面取出数据

 

Intent intent = this.getIntent();        //获取已有的intent对象   
Bundle bundle = intent.getExtras();    //获取intent里面的bundle对象   
String str = bundle.getString("something");    //获取Bundle里面的字符串 

 

用Intent可以直接传递序列化过的类,比如Student类,继承了Serializable接口

public class Student implements Serializable{
	
	private String name;
	private int age;

    public Student(String name,int age){
        this.name=name;
        this.age=age;
    }
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}

}

可以直接通过Intent传递

Student stu=new Student("张三",25);
Intent intent = new Intent(); 
intent.putExtra("student", stu);

一般可以把跳转的代码写到被跳转的页面,如下所示

public class Page extends Activity {
	
	public static void open(Context context,Student stu){
		Intent i = new Intent(context, Page.class);
		i.putExtra("Student", stu);
		context.startActivity(i);
	}
	
}

这样在跳转的时候,只需要调用open函数,便可以跳转,并传递所需要的内容

posted @ 2016-06-07 19:43  黄大仙爱编程  阅读(332)  评论(0编辑  收藏  举报