如果只是兩個活動,那麼你可以使用Bundle來傳遞值。對於兩個以上的活動,建議您使用SharedPreferences。
下面是使用包傳遞值的示例:
String sample="Hello World!";
Bundle b=new Bundle();
b.putString("key_sample",sample);
Intent intent_sample=new Intent(this,Activity_Sample.class);
intent_sample.putExtras(b);
startActivity(intent_sample);
爲了得到傳遞的值:
try{
Bundle get_bundle=getIntent().getExtras();
String get_string=get_bundle.getString("key_sample");
}catch(Exception e){
e.printStackTrace();
}
檢查了這一點:http://www.codestacks.in/2013/03/bundle-values-activities/
SharedPreferences實施例:
public class SharedPreferencesDemo extends Activity {
SharedPreferences shared_preferences;
SharedPreferences.Editor shared_preferences_editor;
String test_string = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
shared_preferences = getSharedPreferences("shared_preferences_test",
MODE_PRIVATE);
test_string = shared_preferences.getString("test_key", "Default");
Toast.makeText(getApplicationContext(), test_string, Toast.LENGTH_SHORT)
.show();
shared_preferences_editor = shared_preferences.edit();
shared_preferences_editor.putString("test_key", "Hello World");
shared_preferences_editor.commit();
test_string=shared_preferences.getString("test_key", "Default");
Toast.makeText(getApplicationContext(), test_string, Toast.LENGTH_SHORT).show();
}
}
下面是完整的解釋:http://www.codestacks.in/sharedpreferences/
我已經實現了一個通用SharedPreferences包裝,一起來看看:http://android-know-how-to.blogspot.co.il/2014/03/androids-shared-preferences.html – TacB0sS 2014-03-13 13:49:07