Example usage for android.content.res Resources updateConfiguration

List of usage examples for android.content.res Resources updateConfiguration

Introduction

In this page you can find the example usage for android.content.res Resources updateConfiguration.

Prototype

@Deprecated
public void updateConfiguration(Configuration config, DisplayMetrics metrics) 

Source Link

Document

Store the newly updated configuration.

Usage

From source file:im.vector.VectorApp.java

/**
 * Get String from a locale/*  w  w  w. ja va 2 s . c o  m*/
 *
 * @param context    the context
 * @param locale     the locale
 * @param resourceId the string resource id
 * @return the localized string
 */
private static String getString(Context context, Locale locale, int resourceId) {
    String result;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        Configuration config = new Configuration(context.getResources().getConfiguration());
        config.setLocale(locale);
        try {
            result = context.createConfigurationContext(config).getText(resourceId).toString();
        } catch (Exception e) {
            Log.e(LOG_TAG, "## getString() failed : " + e.getMessage());
            // use the default one
            result = context.getString(resourceId);
        }
    } else {
        Resources resources = context.getResources();
        Configuration conf = resources.getConfiguration();
        Locale savedLocale = conf.locale;
        conf.locale = locale;
        resources.updateConfiguration(conf, null);

        // retrieve resources from desired locale
        result = resources.getString(resourceId);

        // restore original locale
        conf.locale = savedLocale;
        resources.updateConfiguration(conf, null);
    }

    return result;
}

From source file:de.theknut.xposedgelsettings.ui.MainActivity.java

@SuppressWarnings("deprecation")
@Override//w w  w  .  ja v  a  2 s .  c  om
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mContext = CommonUI.CONTEXT = mActivity = CommonUI.ACTIVITY = this;

    if (getSharedPreferences(Common.PREFERENCES_NAME, Context.MODE_WORLD_READABLE)
            .getBoolean("forceenglishlocale", false)) {
        Resources res = mContext.getResources();
        Configuration conf = res.getConfiguration();
        conf.locale = new Locale(Locale.US.getDisplayLanguage().toLowerCase());
        res.updateConfiguration(conf, res.getDisplayMetrics());
    }

    mTitle = mDrawerTitle = getTitle();
    mFragmentTitles = getResources().getStringArray(R.array.fragmenttitles_array);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    mDrawerLayout.getRootView().setBackgroundColor(CommonUI.UIColor);
    getActionBar().setBackgroundDrawable(new ColorDrawable(CommonUI.UIColor));

    // set a custom shadow that overlays the main content when the drawer opens
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    // set up the drawer's list view with items and click listener
    mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mFragmentTitles));
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
    mDrawerLayout.setOnKeyListener(new OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getRepeatCount() != 0)
                return false;

            if (!mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {

                if ((keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU)) {
                    mDrawerLayout.openDrawer(Gravity.LEFT);
                    return true;
                }
            } else {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    MainActivity.this.finish();
                    return true;
                } else if (keyCode == KeyEvent.KEYCODE_MENU) {
                    mDrawerLayout.closeDrawer(Gravity.LEFT);
                    return true;
                }
            }

            return false;
        }
    });

    // enable ActionBar app icon to behave as action to toggle nav drawer
    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);
    getActionBar().setBackgroundDrawable(new ColorDrawable(CommonUI.UIColor));

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the sliding drawer and the action bar app icon
    mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
            mDrawerLayout, /* DrawerLayout object */
            R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
            R.string.drawer_open, /* "open drawer" description for accessibility */
            R.string.drawer_close /* "close drawer" description for accessibility */
    ) {
        public void onDrawerClosed(View view) {
            getActionBar().setTitle(mTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    SharedPreferences prefs = getSharedPreferences(Common.PREFERENCES_NAME, Context.MODE_WORLD_READABLE);
    CommonUI.NO_BACKGROUND_IMAGE = prefs.getBoolean("nobackgroundimage", false);
    CommonUI.AUTO_BLUR_IMAGE = prefs.getBoolean("autoblurimage", false);

    if (savedInstanceState == null) {

        Intent i = getIntent();
        if (i != null && i.hasExtra("fragment")) {
            if (i.getStringExtra("fragment").equals("badges")) {
                selectItem(6);
            }
        } else {
            selectItem(0);
        }
    }
}

From source file:br.com.frs.foodrestrictions.MessageCannibal.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.activity_message_cannibal, container, false);

    String language = getArguments().getString(MessageLanguageSelector.ARG_LANGUAGE);

    TextView tv = (TextView) v.findViewById(R.id.tvCannibal);

    /* Getting the current resource  and config info */
    Resources rsc = v.getContext().getResources();
    Configuration config = rsc.getConfiguration();
    /* Saving the original locale before changing to the new one
     * just to show the texts//w ww.  j ava  2 s  .c o  m
     */
    Locale orgLocale = config.locale;

    /* Changing the language to the one the user have selected based on the
     * Languages.xml file
     */
    if (language != null) {
        config.locale = new Locale(language);
    }

    /* Setting the new locale */
    rsc.updateConfiguration(config, rsc.getDisplayMetrics());
    /* Updating the layout with the new selected language */
    tv.setText(rsc.getString(R.string.msg_joke_cannibal));

    /* Return to last locale to keep the app as it was before */
    config.locale = orgLocale;
    rsc.updateConfiguration(config, rsc.getDisplayMetrics());

    return v;
}

From source file:ota.otaupdates.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    if (sharedPreferences.getBoolean("force_english", false)) {
        Locale myLocale = new Locale("en");
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;// w ww.ja  va  2s.c o  m
        res.updateConfiguration(conf, dm);
    }

    if (sharedPreferences.getBoolean("apptheme_light", false))
        setTheme(R.style.AppTheme_Light);
    else
        setTheme(R.style.AppTheme_Dark);

    setContentView(R.layout.activity_main);

    build_url
            .append((Utils.doesPropExist(Constants.URL_PROP)) ? Utils.getProp(Constants.URL_PROP)
                    : getString(R.string.download_url))
            .append("/api/").append(Build.DEVICE).append("/").append(Build.TIME / 1000);

    build_dl_url.append((Utils.doesPropExist(Constants.URL_PROP)) ? Utils.getProp(Constants.URL_PROP)
            : getString(R.string.download_url)).append("/builds/");

    delta_url.append((Utils.doesPropExist(Constants.URL_PROP) ? Utils.getProp(Constants.URL_PROP)
            : getString(R.string.download_url))).append("/delta/").append(Build.VERSION.INCREMENTAL);

    delta_dl_url.append((Utils.doesPropExist(Constants.URL_PROP)) ? Utils.getProp(Constants.URL_PROP)
            : getString(R.string.download_url)).append("/deltas/");

    otaList = new ArrayList<>();
    get_builds();
    pb = (ProgressBar) findViewById(R.id.pb);
    pb.setVisibility(View.VISIBLE);

    final ListView ota_list = (ListView) findViewById(R.id.ota_list);

    adapter = new OTAUpdatesAdapter(getApplicationContext(), R.layout.row, otaList);
    ota_list.setAdapter(adapter);

    final CoordinatorLayout coordinator_root = (CoordinatorLayout) findViewById(R.id.coordinator_root);
    ota_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, final int position, long id) {
            final String url = build_dl_url.toString() + otaList.get(position).getOta_filename();

            if (Build.VERSION.SDK_INT >= 23 && !checkPermission())
                allow_write_sd();
            else if (sharedPreferences.getBoolean("disable_mobile", true) && isMobileDataEnabled()) {
                sb_network = Snackbar.make(coordinator_root, getString(R.string.disable_mobile_message),
                        Snackbar.LENGTH_SHORT);
                sb_network.getView()
                        .setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorSecond));
                sb_network.show();
            } else {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        create_notification(1, getString(R.string.app_name), getString(
                                R.string.downloader_notification, otaList.get(position).getOta_filename()));
                        Utils.DownloadFromUrl(url, otaList.get(position).getOta_filename());
                        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(1);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (MD5.checkMD5(otaList.get(position).getOta_md5(),
                                        new File(DL_PATH + otaList.get(position).getOta_filename()))
                                        || !sharedPreferences.getBoolean("md5_checking", true))
                                    trigger_autoinstall(DL_PATH + otaList.get(position).getOta_filename());
                                else {
                                    new AlertDialog.Builder(MainActivity.this)
                                            .setTitle(getString(R.string.md5_title))
                                            .setMessage(getString(R.string.md5_message)).setNeutralButton(
                                                    R.string.button_ok, new DialogInterface.OnClickListener() {
                                                        public void onClick(DialogInterface dialog, int which) {
                                                        }
                                                    })
                                            .show();
                                }
                            }
                        });
                    }
                }).start();
            }
        }
    });

}

From source file:com.money.manager.ex.core.Core.java

private void setAppLocale_Internal(String languageToLoad) {
    Locale locale;//from ww w.j a v a  2s  . co  m

    if (!TextUtils.isEmpty(languageToLoad)) {
        locale = new Locale(languageToLoad);
        //                locale = Locale.forLanguageTag(languageToLoad);
    } else {
        locale = Locale.getDefault();
    }
    // http://developer.android.com/reference/java/util/Locale.html#setDefault%28java.util.Locale%29
    //            Locale.setDefault(locale);

    // change locale of the configuration
    Resources resources = getContext().getResources();
    Configuration config = resources.getConfiguration();

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
        config.locale = locale;
    } else {
        config.setLocale(locale);
    }

    // set new locale
    resources.updateConfiguration(config, resources.getDisplayMetrics());
}

From source file:de.niklasmerz.cordova.fingerprint.Fingerprint.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action          The action to execute.
 * @param args            JSONArry of arguments for the plugin.
 * @param callbackContext The callback id used when calling back into JavaScript.
 * @return A PluginResult object with a status and message.
 *//*  w  w  w .j av a  2s .  c o  m*/
public boolean execute(final String action, JSONArray args, CallbackContext callbackContext)
        throws JSONException {
    mCallbackContext = callbackContext;
    Log.v(TAG, "Fingerprint action: " + action);
    if (android.os.Build.VERSION.SDK_INT < 23) {
        Log.e(TAG, "minimum SDK version 23 required");
        mPluginResult = new PluginResult(PluginResult.Status.ERROR);
        mCallbackContext.error("minimum SDK version 23 required");
        mCallbackContext.sendPluginResult(mPluginResult);
        return true;
    }

    final JSONObject arg_object = args.getJSONObject(0);

    if (action.equals("authenticate")) {
        if (!arg_object.has("clientId") || !arg_object.has("clientSecret")) {
            mPluginResult = new PluginResult(PluginResult.Status.ERROR);
            mCallbackContext.error("Missing required parameters");
            mCallbackContext.sendPluginResult(mPluginResult);
            return true;
        }
        mClientId = arg_object.getString("clientId");
        mClientSecret = arg_object.getString("clientSecret");
        if (arg_object.has("disableBackup")) {
            mDisableBackup = arg_object.getBoolean("disableBackup");
        }
        // Set language
        Resources res = cordova.getActivity().getResources();
        // Change locale settings in the app.
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        //Do not change locale
        res.updateConfiguration(conf, dm);

        if (isFingerprintAuthAvailable()) {
            SecretKey key = getSecretKey();
            boolean isCipherInit = true;
            if (key == null) {
                if (createKey()) {
                    key = getSecretKey();
                }
            }
            if (key != null && !initCipher()) {
                isCipherInit = false;
            }
            if (key != null) {
                cordova.getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        // Set up the crypto object for later. The object will be authenticated by use
                        // of the fingerprint.
                        mFragment = new FingerprintAuthenticationDialogFragment();
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("disableBackup", mDisableBackup);
                        mFragment.setArguments(bundle);

                        if (initCipher()) {
                            mFragment.setCancelable(false);
                            // Show the fingerprint dialog. The user has the option to use the fingerprint with
                            // crypto, or you can fall back to using a server-side verified password.
                            mFragment.setCryptoObject(new FingerprintManager.CryptoObject(mCipher));
                            mFragment.show(cordova.getActivity().getFragmentManager(), DIALOG_FRAGMENT_TAG);
                        } else {
                            if (!mDisableBackup) {
                                // This happens if the lock screen has been disabled or or a fingerprint got
                                // enrolled. Thus show the dialog to authenticate with their password
                                mFragment.setCryptoObject(new FingerprintManager.CryptoObject(mCipher));
                                mFragment.setStage(
                                        FingerprintAuthenticationDialogFragment.Stage.NEW_FINGERPRINT_ENROLLED);
                                mFragment.show(cordova.getActivity().getFragmentManager(), DIALOG_FRAGMENT_TAG);
                            } else {
                                mCallbackContext.error("Failed to init Cipher and backup disabled.");
                                mPluginResult = new PluginResult(PluginResult.Status.ERROR);
                                mCallbackContext.sendPluginResult(mPluginResult);
                            }
                        }
                    }
                });
                mPluginResult.setKeepCallback(true);
            } else {
                mCallbackContext.sendPluginResult(mPluginResult);
            }

        } else {
            mPluginResult = new PluginResult(PluginResult.Status.ERROR);
            mCallbackContext.error("Fingerprint authentication not available");
            mCallbackContext.sendPluginResult(mPluginResult);
        }
        return true;
    } else if (action.equals("isAvailable")) {
        if (isFingerprintAuthAvailable() && mFingerPrintManager.isHardwareDetected()
                && mFingerPrintManager.hasEnrolledFingerprints()) {
            mPluginResult = new PluginResult(PluginResult.Status.OK);
            mCallbackContext.success();
        } else {
            mPluginResult = new PluginResult(PluginResult.Status.ERROR);
            mCallbackContext.error("Fingerprint authentication not ready");
        }
        mCallbackContext.sendPluginResult(mPluginResult);
        return true;
    }
    return false;
}

From source file:com.ericsun.duom.Framework.Activity.BaseActivity.java

@Override
public Resources getResources() {
    Resources res = super.getResources();
    Configuration config = new Configuration();
    //        config.setToDefaults();
    config.fontScale = 1.0f;/*from   w w  w  .  j  av  a 2 s  .c  om*/
    res.updateConfiguration(config, res.getDisplayMetrics());
    return res;
}

From source file:abanoubm.dayra.main.Main.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    if (Utility.getArabicLang(getApplicationContext()) == 1) {
        Utility.setArabicLang(getApplicationContext(), 2);

        Locale myLocale = new Locale("ar");
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;//from w  ww .j  a v  a  2  s.  c om
        res.updateConfiguration(conf, dm);

        finish();
        startActivity(new Intent(getIntent()));
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.act_main);
    ((TextView) findViewById(R.id.subhead1)).setText(R.string.app_name);
    ((TextView) findViewById(R.id.subhead2)).setText(BuildConfig.VERSION_NAME);
    findViewById(R.id.nav_back).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            finish();

        }
    });
    ((TextView) findViewById(R.id.footer)).setText("dayra " + BuildConfig.VERSION_NAME + " @"
            + new SimpleDateFormat("yyyy", Locale.getDefault()).format(new Date()) + " Abanoub M.");

    if (!Utility.getDayraName(getApplicationContext()).equals("")) {
        startActivity(new Intent(getApplicationContext(), Home.class));
        finish();
    }

    ListView lv = (ListView) findViewById(R.id.home_list);

    mMenuItemAdapter = new MenuItemAdapter(getApplicationContext(),
            new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.sign_menu))), 1);
    lv.setAdapter(mMenuItemAdapter);

    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {
            case 0:
                sign();
                break;
            case 1:
                register();
                break;
            case 2:
                if (Build.VERSION.SDK_INT < 23 || ContextCompat.checkSelfPermission(Main.this,
                        Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    importDB();
                } else {
                    ActivityCompat.requestPermissions(Main.this,
                            new String[] { android.Manifest.permission.READ_EXTERNAL_STORAGE }, IMPORT_REQUEST);
                }
                break;
            case 3:
                startActivity(new Intent(Intent.ACTION_VIEW).setData(
                        Uri.parse("https://drive.google.com/file/d/0B1rNCm5K9cvwVXJTTzNqSFdrVk0/view")));
                break;
            case 4:
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(
                        "https://drive.google.com/open?id=1flSRdoiIT_hNd96Kxz3Ww3EhXDLZ45FhwFJ2hF9vl7g")));
                break;
            case 5: {

                AlertDialog.Builder builder = new AlertDialog.Builder(Main.this);
                builder.setTitle(R.string.label_choose_language);
                builder.setItems(getResources().getStringArray(R.array.language_menu),
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String temp;
                                if (which == 1) {
                                    temp = "en";
                                    Utility.setArabicLang(getApplicationContext(), 0);
                                } else {
                                    temp = "ar";
                                    Utility.setArabicLang(getApplicationContext(), 2);
                                }
                                Locale myLocale = new Locale(temp);
                                Resources res = getResources();
                                DisplayMetrics dm = res.getDisplayMetrics();
                                Configuration conf = res.getConfiguration();
                                conf.locale = myLocale;
                                res.updateConfiguration(conf, dm);

                                finish();
                                startActivity(new Intent(getIntent()));
                            }

                        });
                builder.create().show();

            }
                break;
            case 6:
                try {
                    getPackageManager().getPackageInfo("com.facebook.katana", 0);
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/453595434816965"))
                            .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
                } catch (Exception e) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/dayraapp"))
                            .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
                }
                break;

            case 7:

                try {
                    getPackageManager().getPackageInfo("com.facebook.katana", 0);
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/1363784786"))
                            .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
                } catch (Exception e) {
                    startActivity(
                            new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/EngineeroBono"))
                                    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
                }
                break;
            case 8:
                Uri uri = Uri.parse("market://details?id=" + getPackageName());
                Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
                try {
                    startActivity(goToMarket);
                } catch (Exception e) {
                    startActivity(new Intent(Intent.ACTION_VIEW,
                            Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
                }
                break;
            case 9:
                if (Build.VERSION.SDK_INT < 23 || ContextCompat.checkSelfPermission(Main.this,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent(Intent.ACTION_VIEW).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                    intent.setDataAndType(Uri.fromFile(new File(Utility.getDayraFolder())), "*/*");
                    startActivity(
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
                } else {
                    ActivityCompat.requestPermissions(Main.this,
                            new String[] { android.Manifest.permission.WRITE_EXTERNAL_STORAGE },
                            FOLDER_REQUEST);
                }
                break;
            case 10:
                LayoutInflater li = LayoutInflater.from(getApplicationContext());
                final View aboutView = li.inflate(R.layout.dialogue_about, null, false);
                final AlertDialog ad = new AlertDialog.Builder(Main.this).setCancelable(true).create();
                ad.setView(aboutView, 0, 0, 0, 0);
                ad.show();
                ((TextView) aboutView.findViewById(R.id.about))
                        .setText(String.format(getResources().getString(R.string.copyright),
                                Calendar.getInstance().get(Calendar.YEAR)));

                ((TextView) aboutView.findViewById(R.id.notice)).setText(GoogleApiAvailability.getInstance()
                        .getOpenSourceSoftwareLicenseInfo(getApplicationContext()));
                aboutView.findViewById(R.id.btn).setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        ad.cancel();
                    }
                });
                break;
            }
        }
    });

}

From source file:br.com.frs.foodrestrictions.FoodMessages.java

@Override
public void onItemSelected(AdapterView<?> adapterView, View v, int i, long l) {

    /* //TODO - Find a better way of doing it
     * I don't believe that this is the best approach to handle this problem but it is
     * the only way I found to do it so far. Do you have any better idea?
     * please help me here :D/*  w w w  . ja v  a2  s  .c  om*/
     */

    /* Getting the current resource  and config info */
    Resources rsc = v.getContext().getResources();
    Configuration config = new Configuration(rsc.getConfiguration());
    /* Saving the original locale before changing to the new one
     * just to show the texts
     */
    Locale orgLocale = config.locale;

    /* Changing the language to the one the user have selected based on the
     * Languages.xml file
     */
    switch (i) {
    /* English */
    case 0:
        config.locale = new Locale("en");
        break;
    /* Portuguese */
    case 1:
        config.locale = new Locale("pt");
        break;
    }

    /* Setting the new locale */
    rsc.updateConfiguration(config, rsc.getDisplayMetrics());
    refreshMessages(v);

    /* Updating the layout with the new selected language */

    /* Return to last locale to keep the app as it was before */
    config.locale = orgLocale;
    rsc.updateConfiguration(config, rsc.getDisplayMetrics());
}

From source file:mobile.tiis.appv2.LoginActivity.java

public void setLocale(String lang) {

    myLocale = new Locale(lang);
    Resources res = getResources();
    DisplayMetrics dm = res.getDisplayMetrics();
    Configuration conf = res.getConfiguration();
    conf.locale = myLocale;//from  w  w  w.j  a v  a  2s .  c om
    res.updateConfiguration(conf, dm);
    Intent refresh = new Intent(this, LoginActivity.class);
    refresh.putExtra(BackboneActivity.LANGUAGELOGIN, languagePosition);
    startActivity(refresh);
}