我有以下問題:共享首選項Android
我編碼了一個包含2個活動的android應用程序。第一個Activity
是主要活動,第二個是設置。
在設置Activity
中,您可以在EditText
框中輸入您的姓名,該姓名應該在第一個Activity
中顯示爲問候語。
我怎樣才能以非常簡單的方式做到這一點?
我有以下問題:共享首選項Android
我編碼了一個包含2個活動的android應用程序。第一個Activity
是主要活動,第二個是設置。
在設置Activity
中,您可以在EditText
框中輸入您的姓名,該姓名應該在第一個Activity
中顯示爲問候語。
我怎樣才能以非常簡單的方式做到這一點?
對此有兩種方法。
第一:onActivityResult
在主要活動:
使用startActivityForResult(intent, ACTIVITY2)
並添加此方法
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent intent)
{
if (resultCode == Activity.RESULT_OK)
{
String string_1 = intent.getStringExtra ("my_value_from_second_activity", "");
}
}
在設置的活動:
Intent intent = new Intent();
intent.putExtra ("my_value_from_second_activity", "hello");
activity.setResult (Activity.RESULT_OK, intent);
二:SharedPreferences的好辦法
制定活動:
SharedPreferences settings = getSharedPreferences("config", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("my_value", edttext.getText().toString());
editor.commit();
主要Ativity:
SharedPreferences settings = getSharedPreferences("config", 0);
String value = settings.getString("my_value", "");
你想要這樣做SharedPreferences
?這是您從設置活動中保存數據的方式。添加一個按鈕,一旦你介紹的名字,以節省您的喜好,把這個代碼上點擊收聽:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putString("NAME", yourEditText.getText().toString());
editor.commit();
然後在您的主要活動,添加一個按鈕和一個TextView顯示的名稱。將下面的代碼添加到按鈕:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = sharedPreferences.getString("NAME", null);
yourTextView.setText(name); //Add the name to your textview
希望它有幫助!
您可以通過意圖從一個活動傳遞數據到另一個 您也可以使用s的常量類tatic變量存儲值 和共享的prefrenct存儲數據,直到apk安裝程序,所以你可以使用一個
[如何在活動之間傳遞數據](http://stackoverflow.com/questions/2091465/how-do -i-pass-data-between-activities-in-android) – ThaMe90
查看[developer.android.com]上的指南(http://developer.android.com/guide/topics/ui/settings.html ) – germi
您可以閱讀本教程中的所有內容:http://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html#preferences –