1. 程式人生 > >Android 使用Intent和Bundle傳遞資料及如何傳遞enum

Android 使用Intent和Bundle傳遞資料及如何傳遞enum

                       

轉載請標明出處:http://blog.csdn.net/xx326664162/article/details/50754571   文章出自:薛瑄的部落格

你也可以檢視我的其他同類文章,也會讓你有一定的收貨!

  • 在兩個Activity之間傳遞資料,最終都是通過bundle傳遞,
  • Intent的Extra屬性就是Bundle物件,
  • Bundle物件就是一個Map物件

下面的示例中是以存取enum型別的資料為例

方法一:

使用Intent便捷方式,這些方法是直接存取Intent所攜帶的Bundle中的資料
put

intent.putExtra(String "name", Xxx value)//向Intent中按key-value對的形式存入資料
   
  • 1

示例:

Intent intent = new Intent(MainActivity.this,OtherActivity.class);intent.putExtra("enum", YourEnum.TYPE
1);
  • 1
  • 2

get

intent.getXxxExtra(String key);//從Intent中按key取出指定型別的資料,例如getStringExtra(),取出String型別資料
   
  • 1
  • 2

示例:

Intent intent = getIntent();YourEnum TYPE1 = (YourEnum ) intent.getSerializableExtra("enum");
   
  • 1
  • 2

方法二:

使用Bundle物件的方法存入資料:

put

bundle.
putXxx(String key , Xxx data) ; //向Bundle放入Int、String各種資料型別bundle.putSerializable(String key , Seralizable data) //向Bundle放入一個可序列化的物件,例如:enum
  • 1
  • 2
  • 3

示例:

Intent intent = new Intent(MainActivity.this,OtherActivity.class);Bundle bundle = new Bundle();bundle.putSerializable("enum", YourEnum.TYPE1);intent.putExtras(bundle);     //將bundle傳入intent中。
   
  • 1
  • 2
  • 3
  • 4

get

bundle.getXxx(String key);//從Bundle取出Int、String等各種型別的資料bundle.gutSerializable(String key ) //從Bundle取出一個可序列化的物件,例如:enum
   
  • 1
  • 2

示例:

Intent intent = getIntent();Bundle bundle = intent.getExtras();YourEnum TYPE1 = (YourEnum ) bundle.get("enum");//這時使用get()取出一個Object型別的物件,可以進行強制型別轉化。
   
  • 1
  • 2
  • 3

參考:http://stackoverflow.com/questions/3293020/android-how-to-put-an-enum-in-a-bundle

http://blog.csdn.net/neu_yousei/article/details/21953995

 

關注我的公眾號,輕鬆瞭解和學習更多技術
  這裡寫圖片描述

           

再分享一下我老師大神的人工智慧教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智慧的隊伍中來!https://blog.csdn.net/jiangjunshow