2013-04-24 34 views
0

當用戶從設置中選擇選項時,我必須更改一個文本,例如 當用戶從選項中選擇它時,必須將公里更改爲英里。而當我選擇它 我必須改變公里成英里思想的應用程序,請幫助我,如果有人知道 如何做到這一點?如何在Android的整個應用程序中用另一個字符串替換一個字符串?

+0

使用sharedpreferences – Senthil 2013-04-24 09:10:29

+0

進一步解釋,它是一個列表?一個文本視圖還是什麼? – 2013-04-24 09:12:23

回答

2

聲明這些全球範圍內爲方便:

SharedPreferences sharedPrefs; 
Editor editor; 
private static final String PRIVATE_PREF = "current_selection"; 

然後在onCreate()或同類產品:

sharedPrefs = getApplicationContext().getSharedPreferences(PRIVATE_PREF, Context.MODE_PRIVATE); 

// SET THE DEFAULT VALUE 
editor = sharedPrefs.edit(); 
editor.putString("value", "kilometers"); 

// DONT SKIP THIS STEP 
editor.commit(); 

最後,無論你需要檢查其中兩個是當前選擇的值( 公里/英里):

String strSetting = sharedPrefs.getString("value", null); 

現在,您可以使用String strSetting來檢查設置的值,並運行相應的代碼。我認爲它可能與轉換有關。

注:如果您使用的是上述另一Activity(檢索),您將需要再次實例化這樣的:你要更改設置

SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences(PRIVATE_PREF, Context.MODE_PRIVATE); 
String strSetting = sharedPrefs.getString("value", null); 

任何時候,只要使用第一段代碼。例如,如果你改變公里邁爾斯:

// SET THE A NEW VALUE 
editor = sharedPrefs.edit(); 
editor.putString("value", "miles"); 

// DONT SKIP THIS STEP 
editor.commit(); 

你可以閱讀更多關於SharedPreferences here

0

在MainActivity(或其他地方)聲明一個靜態字符串。

class MainActivity { 
    public static String distance = "kilometer"; 
} 

可以從任何位置改變字符串

MainActivity.distance = "miles"; 

然後你可以使用距離字符串印花布您的應用程序。

+1

好..但它的工作一次..當我再次啓動應用程序然後它給我「公里」; – 2013-04-24 09:19:17

+0

然後搜索SharedPreferences,你會發現很多關於如何使用它們的信息。寫一個布爾值或一個字符串或其他什麼SHaredPrefs,包含用戶選擇。當您的應用加載時,您將加載SharedPref並相應地設置全局靜態「距離」。 – FWeigl 2013-04-24 09:48:27

相關問題