Android開發(fā)數(shù)據(jù)傳遞方法的方法是多種多樣的,那么Activity間傳遞的數(shù)據(jù)通常相對簡單,但在實(shí)際開發(fā)中有時會傳遞更復(fù)雜的數(shù)據(jù),那么android開發(fā)時Activity中傳遞變量的參數(shù)大家都了解嗎?下面就跟著武林技術(shù)頻道小編的步伐一起來了解一下吧!
保存參數(shù)時:
Intent intent = new Intent();
intent.setClass(A.this, B.class);
Bundle bundle = new Bundle();
bundle.putString("name", "xiaozhu");
intent.putExtras(bundle);
startActivity(intent);
讀取參數(shù):
?
?
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
String name = bundle.getString("name");
[java] view plaincopy
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
String name = bundle.getString("name");
不過在多個Activity中經(jīng)常使用同一變量時,使用Bundle則比較麻煩,每次調(diào)用Activity都需要設(shè)置一次。
如想在整個應(yīng)用中使用,在java中一般是使用靜態(tài)變量,而在android中有個更優(yōu)雅的方式是使用Application context。
新建一個類,繼承自Application
?
?
class MyApp extends Application {
private String myState;
public String getState() {
return myState;
}
public void setState(String s) {
myState = s;
}
}
在AndroidManifest.xml的application加個name屬性就可以了,如下面所示:
?
?
使用時:
?
?
class Blah extends Activity {
@Override
public void onCreate(Bundle b){
...
MyApp appState = ((MyApp)getApplicationContext());
String state = appState.getState();
...
}
}
上文是關(guān)于android開發(fā)時Activity中傳遞變量的參數(shù)介紹,相信大家都有了一定的了解,想要了解更多的相關(guān)介紹,請繼續(xù)關(guān)注武林技術(shù)頻道吧!