1.介紹
對於初學者android不同activity間的資料轉送一直是一個難題,主要的解決方案主要有兩種一種是用Bundle傳輸資料,一種是用SharedPreferences。兩者的區別,一般來講SharedPreferences用來儲存輕型資料,儲存在xml裡,可以持久儲存。反觀Bundle可以傳輸很多中資料,但是不持久。
2.具體實現方法 Bundle
在發送方class A
Bundle bundle = new Bundle(); //儲存輸入的資訊 bundle.putString("string名", "傳輸的string"); Intent intent=new Intent(A.this,B.class); intent.putExtras(bundle);
在接收方class B
Bundle b=getIntent().getExtras(); //擷取Bundle的資訊 String info=b.getString("string名");
注意:string名要一樣
SharedPreferences
SharedPreferences 用法很簡單,如果你想要編輯SharedPreferences中的內容就需要用到editor對象。
在發出方A中
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext()); Editor editor = sp.edit(); editor.putString("string變數名","發出的string內容"); editor.commit();
接收方B
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(B.this); string grade = sp.getString("string變數名",“預設值”);
查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/