標籤:android blog ar sp java strong 資料 div on
Android開發中,在不同模組(如Activity)間經常會有各種各樣的資料需要相互傳遞,常用的的有五種傳遞方式。它們各有利弊,有各自的應用情境。下面分別介紹一下:
1、 Intent對象傳遞簡單資料
Intent的Extra部分可以儲存傳遞的資料,可以傳送int, long, char等一些基礎類型。
[1]傳遞頁面:
Intent intent = new Intent();intent.setClass(MainActivity.this, SecondActivity.class);Bundle bundle = new Bundle(); //打包發送bundle.putString("name","123"); //綁定參數intent.putExtra("maps",bundle);startActivity(intent);
[2]接收頁面:
@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); Intent intent = this.getIntent(); Bundle bundle = intent.getBundleExtra("maps"); //擷取打包資料bundle String name = bundle.getString("name"); //取出需要的資料 tv.setText(name); setContentView(tv);}或者@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second); TextView txt = (TextView)this.findViewById(R.id.txt); Intent intent = this.getIntent(); Bundle bundle = intent.getBundleExtra("maps"); //擷取打包資料bundle String name = bundle.getString("name"); //取出需要的資料 txt.setText(name); }
2.、Intent對象傳遞複雜資料
有時候我們想傳遞如ArrayList之類複雜些的資料,這種原理是和上面一種是一樣的,只是在傳參數前,要用新增加一個List將對象包起來。如下:
Android 之資料傳遞小結