如何使用Context包装器在运行时更改应用程序语言?

时间:2017-09-16 08:31:36

标签: java android localization sharedpreferences

我想添加一个使用共享首选项更改应用程序语言的选项。我在共享偏好设置中保存了“en”或“fa”等语言。

现在我需要将共享首选项数据设置为语言。我尝试使用This code但我遇到了一些问题。

为了使用这段代码,我应该用以下内容包装我的活动:

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(MyContextWrapper.wrap(newBase,languageFromPrefs));
}

我编写了一种方法,用于从共享首选项中获取名为getString(Context context,String key,String defaultValue)的语言,然后将该代码编辑为:

@Override
protected void attachBaseContext(Context newBase) {
    lang = App.Prefs.getString(newBase, App.Prefs.LANGUAGE_KEY,"fa");
    super.attachBaseContext(MyContextWrapper.wrap(newBase,lang));
}

看起来不错但是当我运行我的应用程序时,我看到了一个奇怪的场景。首次运行时,app语言为fa(波斯语),下次自动更改为en(英语)!

[注意:设备语言目前是英文]


这是我的主要活动:

(我评论了与我的问题无关的代码)

public class MainActivity extends AppCompatActivity {

    EditText userText;
    Button embellishBtn;
    ImageView settings;
    String lang;

    @Override
    protected void attachBaseContext(Context newBase) {
        lang = App.Prefs.getString(newBase, App.Prefs.LANGUAGE_KEY,"fa");
        super.attachBaseContext(App.wrap(newBase,lang));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
/*
        userText = (EditText) findViewById(R.id.textBox);
        embellishBtn = (Button) findViewById(R.id.embellishButton);
        settings = (ImageView) findViewById(R.id.settings);

        App.SetFont.EditText(userText,this);
        App.SetFont.Button(embellishBtn,this);

        settings.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(getBaseContext(),getString(R.string.settings),Toast.LENGTH_SHORT).show();
                return true;
            }
        });

        MarginActivity.isFirstRateMessage = true;



        Boolean isFirstOpen = App.Prefs.getBoolean(this, App.Prefs.FIRST_OPEN_KEY,true);

        if (isFirstOpen && TimeZone.getDefault().getDisplayName().toLowerCase().equals("iran standard time"))
        {
            App.Prefs.setString(this, App.Prefs.LANGUAGE_KEY,"fa");
            App.Prefs.setBoolean(this,App.Prefs.FIRST_OPEN_KEY,false);
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }
        */
    }
/*
    public void onSettingsClick(View view)
    {
        startActivity(new Intent(this, SettingsActivity.class));
    }

    public void onEmbellishClick(View view)
    {
        if(userText.getText().toString().trim().length() > 0)
        {
            Intent intent = new Intent(this,EmbellishActivity.class);
            intent.putExtra("user_text",userText.getText().toString() + " ");

            startActivity(intent);
        }
        else
        {
            Animation shake = AnimationUtils.loadAnimation(this,R.anim.focus_zoom);
            userText.startAnimation(shake);
        }
        userText.setText(null);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("user_text",userText.getText().toString());
    }
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        userText.setText(savedInstanceState.getString("user_text"));
    }
    */
}

和getString方法App.Prefs.getString()):

static String getString(Context context,String key,String defaultValue)
{
    SharedPreferences shared = context.getSharedPreferences("Prefs", MODE_PRIVATE);
    return shared.getString(key, defaultValue);
}


我的应用程序运行没有任何错误。 我应该怎么做才能解决这个问题?怎么了?

2 个答案:

答案 0 :(得分:0)

您必须在运行时使用这种方式更改语言

  SharedPreferences LanguagePreference = getSharedPreferences("SelectedLanguage", 0);
    String languageToLoad  = LanguagePreference.getString("Language", null);
    Locale locale =null;
    if(languageToLoad!=null && languageToLoad.equals("english"))
        locale =new Locale("en", "US");
    else if(languageToLoad!=null && languageToLoad.equals("tamil"))
        locale =new Locale("ta", "IN");
    else
        locale =new Locale("en", "US");
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.setLocale(locale);
    getBaseContext().getResources().updateConfiguration(config,
            getBaseContext().getResources().getDisplayMetrics());

答案 1 :(得分:0)

@Override 
 protected void attachBaseContext(Context newBase) {
 super.attachBaseContext(MyContextWrapper.wrap
 (newBase,languageFromPrefs));
 }

这应该在基础活动中完成,基础活动由项目中的每个活动扩展。