安卓Activity跳轉

安卓Activity跳轉

分爲三步:

  1. 創建Intent對象
  2. 設置從哪跳轉到哪setClass
  3. 跳轉startActivity
	Intent intent = new Intent();
	intent.setClass(MainActivity.this, // context
	                        NewActivity.class); // class
    //跳轉到新的Activity
	startActivity(intent);//不傳遞數據,並且不需要返回響應

跳轉時攜帶數據

有三種攜帶方法

  1. 直接putExtra以鍵值對的方式存儲

  2. 都封裝在Bundle對象中,將Bundle對象以鍵值對的方式存儲

  3. 傳遞一個自定義的對象

1.putExtra的直接存儲方式

類似於下面的方法,在取出時注意類型

	// 存儲
	intent.putExtra("phone", "1234565");
	intent.putExtra("email", "123132ees");
	// 另一個Activity中接收,如果存的時int就是getIntExtra
	String phone = request.getStringExtra("phone");
	String email = request.getStringExtra("email");

2.封裝成Bundle的存儲方式

	// 存儲
	Bundle bundle = new Bundle(); // 創建Bundle對象
	bundle.putString("phone","123231121212"); // 放入什麼類型的就putXXX()
	bundle.putString("email","adadasda");
	intent.putExtra("bundle",bundle);
	// 另一個Activity中接收
	Bundle bundle = request.getBundleExtra("bundle");
	String phone = bundle.getString("phone");
	String email = bundle.getString("email");

3.傳遞一個自定義的對象

	// 存儲
	Student student = new Student("張三","121312312","123121");
	intent.putExtra("stu",student);
	// 另一個Activity中接收
	Student stu = (Student) request.getSerializableExtra("stu");
	String phone = stu.getPhone();
	String email = stu.getEmail();

PS:當傳遞一個自定義的對象時,該類需要實現Serializable接口,上面的例子中Student類實現了Serializable接口。(Serializable接口中沒有任何需要實現的方法,直接implements即可)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章