如何在Android的整个应用程序中用另一个字符串替换一个字符串?

如何在Android的整个应用程序中用另一个字符串替换一个字符串?

问题描述:

当用户从设置中选择选项时,我必须更改一个文本,例如 当用户从选项中选择它时,必须将公里更改为英里。而当我选择它 我必须改变公里成英里思想的应用程序,请帮助我,如果有人知道 如何做到这一点?如何在Android的整个应用程序中用另一个字符串替换一个字符串?

+0

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

+0

进一步解释,它是一个列表?一个文本视图还是什么? – 2013-04-24 09:12:23

声明这些全球范围内为方便:

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

在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