Bundle傳遞引數

2021-07-30 03:59:24 字數 1638 閱讀 3223

bundle是在android中十分有用的一種類,我們通常用它來進行引數的傳遞。理解bundle可以把它當作乙個map,所以它的本質是乙個key-value鍵值對。其中key值為乙個標識引數的string值,value即為該string對應的引數。

使用bundle傳遞引數會在intent、message、fragment中用到,下面就總結一下這幾種情況下用bundle封裝引數以及取出引數的寫法。

1.intent(兩個activity的信使)使用bundle傳遞引數:

傳送:

bundle bundle = new bundle(); 

bundle.putstring("name" , "lily");

bundle.putdouble("score" , 89.7);

intent intent = new intent();

intent.putextras(bundle);

intent.setclass(thisone.this , thatone.class);

startactivity(intent);

接收:

bundle bundle = this.getintent().getextras();

string name = bundle.getstring("name");

double score = bundle.getdouble("score");

或者傳送:

intent.putextra("date", selectdate);
接收:

intent.getextras().getstring("date")

2.message(常常跟handler結合使用)使用bundle傳遞引數:

使用message機制主要是為了保證執行緒之間操作安全,同時不需要關心具體的訊息接收者,使訊息本身和執行緒剝離開,這樣就可以方便的實現定時、非同步等操作。

傳送:

message msg = new message();

msg.what = 0x123;

bundle b = new bundle();

b.putint("age" , 20);

b.putstring("name" , "lily");

msg.setdata(b);

接收:

handler myhandler = new handler

}

3.在fragment(activity片段)中使用bundle傳遞引數

傳送:

bundle args = new bundle();

args.putint("","");

args.putstring("","");

frament.setarguments(key, int);

接收:

bundle args = getarguments();

string data = args.getint(key);

string str = args.getstring(key);

Bundle類用於傳遞值

android中bundle類的作用 bundle類用作攜帶資料,它類似於 map,用於存放 key value 名值對形式的值。相對於 map,它提供了各種常用型別的 put get 方法,如 putstring getstring 和putint getint put 用於往bundle 物件放...

使用EventBus代替Bundle傳遞引數。

註冊 eventbus.getdefault register this 反註冊 eventbus.getdefault unregister this post方法 eventbus.getdefault post obj 接收方法 如果使用onevent作為訂閱函式,那麼該事件在哪個執行緒發布出...

Activity之間利用Bundle傳遞資料

import android.content.intent import android.os.bundle import android.view.view import android.widget.edittext activity的使用.4句概述 1 負責使用者互動,提供介面,有自己的生命週...