關於Intent傳遞資料的幾種方法

2021-07-04 01:19:57 字數 2683 閱讀 8217

(1)首先是activity的簡單跳**

activity的切換一般是通過intent來實現的,intent是乙個activity到達另乙個activity的引路者,它描述了起點(當前activity)和終點(目標activity)。乙個簡單intent實現如下: 

intent intent = new intent(); 

//建立乙個intent物件 

intent.setclass(activity1.this, activity2.class); 

//描述起點和目標 

startactivity(intent); 

//開始跳轉 

(2)通常,我們在activity的切換中,希望把前乙個activity的某些資料傳遞給下乙個activity。這時,我們可以借助bundle來實現。bundle,相當於資料儲存包,用於存放我們想要轉達的資料。打個比方,intent就像一封郵件,裡面有送信人位址(原始activity),也有收信人位址(目標activity),而bundle就是附件也可看做是信件內容。下面是它的簡單實現:

a、activity1傳送: 

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); 

//開始切換 

b、activity2接受從activity1發來的資料:

intent intent = this.getintent(); 

//獲取已有的intent物件 

bundle bundle = intent.getextras(); 

//獲取intent裡面的bundle物件 

string = bundle.getstring("something"); 

//獲取bundle裡面的字串 

a、從activity1切換到activity2: 

intent intent = new intent(); 

intent = intent.setclass(activityintent.this, anotheractivity.class); 

bundle bundle = new bundle(); 

bundle.putstring("string", et_string.gettext().tostring()); 

intent.putextras(bundle); 

startactivityforresult(intent,0); 

//只有這裡不同 

//不能用finish,會觸發ondestroy(); 

b、從activity2返回到activity1:

intent intent = new intent(); 

intent = intent.setclass(anotheractivity.this, activityintent.class); 

bundle bundle = new bundle(); 

bundle.putint("result", "activity2的處理結果"); 

intent.putextras(bundle); 

anotheractivity.this.setresult(result_ok, intent); 

//result_ok是返回狀態碼 

anotheractivity.this.finish(); //會觸發ondestroy(); 

c、activity1接受activity2的返回結果: 

protected void onactivityresult(int requestcode, int resultcode, intent data)  

}  (4)、從activity2中返回到activity1(在activity1切換到activity2時,呼叫了finish方法),你會發現你在activity1以前的資料全沒了,簡單的說就是資料被沒有保留下來。因為finish方法,會觸發ondestroy(),使得activity1銷毀。下一次再來到activity1時,是全新的activity1,以往的資料當然不在。如果想保留切換前的狀態,可以採用兩種方式:1、切換時,不呼叫finish()方法。2、採用sharedpreferences來儲存資料。sharedpreferences 是乙個輕量級儲存類,主要用於儲存一些窗體的狀態,如文字框值、按鈕狀態等等,類似於session。一般在onpause()方法裡面儲存資料,在onresume()裡面提取資料。實現如下:

a、儲存資料 

//暫停:onstart()->onresume()->onpause() 

@override 

protected void onpause()  

b、提取資料 

//重啟:onstart()->onresume() 

@override 

protected void onresume()  

Intent 傳遞資料

intent 可傳遞的資料型別 可傳輸的資料型別 a.基本資料型別 陣列 b.string 陣列 c.bundle map d.serializable bean e.parcelable 放在記憶體乙個共享空間裡 基本型別 intent intent new intent this,otherac...

Intent資料的傳遞

1.intent明確的intent,直接以類名制定要啟動哪乙個activity,通常用 與啟動自己額的activity,2.隱試的intent 所謂隱試,就是只有intent中指出想要進行的操作,例如 撥號,顯示,編輯,搜尋,以及,資料,例如 號碼,email,等 讓系統幫助我們找出合適的activ...

Intent的資料傳遞

雖然知識非常基礎,但我覺得無論是否是難點,即便非常簡單的知識,及時寫出來對知識積累都是有好處的。今天寫一下intent的資料傳遞。傳送端 建立intent intent intent new intent 把需要傳遞的內容放進intent intent.putextra id waitinfo.id...