Android 之資料傳遞小結

來源:互聯網
上載者:User

標籤: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 之資料傳遞小結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.