public void English (View view) {
if (toggleButton.isChecked()) {
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("selectedlanguage", "English");
editor.commit();
Toast.makeText(getBaseContext(), sharedPref.getString("selectedlanguage", null) + " is the default page", Toast.LENGTH_SHORT).show();
English();
}
else English();
以后使用我想使用editor.putString("selectedlanguage", "English");
“英语”作为班级名称。
像这样:
if (sharedPref.getString("selectedlanguage", null) != null) {
//use the "English" as class name so it will execute the class
}
答案 0 :(得分:1)
关闭你的问题和评论,我假设你只想根据SharedPreferences
中存储的值创建一个类。我还假设您要创建多个“语言”,并从SharedPreferences
值启动相应的类。为此我会使用Factory pattern:
首先,创建一个“语言”interface
,其中包含所有语言类的常用方法:
public interface Language {
//Example
void speak();
}
其次,让所有语言类都实现此接口:
public class English implements Language {
@Override
public void speak() {
Log.i("Tag", "English");
}
}
public class Chinese implements Language {
@Override
public void speak() {
Log.i("Tag", "Chinese");
}
}
第三,创建一个构建“语言”类的Factory类:
public class LanguageFactory {
public static final int LANGUAGE_ENGLISH = 100;
public static final int LANGUAGE_CHINESE = 101;
public Language getLanguage(int code) {
Language language = null;
switch (code) {
case LANGUAGE_ENGLISH:
language = new English();
break;
case LANGUAGE_CHINESE:
language = new Chinese();
break;
}
return language;
}
}
现在,每当您保存到共享首选项时,请使用:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("selectedlanguage", LanguageFactory.LANGUAGE_ENGLISH);
editor.commit();
然后,当您想使用存储的值时:
int languageCode = sharedPref.getInt("selectedLanguage", -1);
LanguageFactory factory = new LanguageFactory();
Language language = factory.getLanguage(languageCode);
在这种情况下,“语言”将是“英语”,但它会根据您存储到SharedPreferences
的“代码”而改变。这是一个非常灵活的系统,允许您将来添加新语言,并且当您使用常量时,由于提供不正确的值而导致错误的可能性要小得多。
答案 1 :(得分:0)
请看这个
Class<?> c = null;
if(StringClassname != null) {
try {
c = Class.forName(StringClassname );
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}