I am aware of Creating a new values directory for the language with the suffix of the language code. For german: values-de or french: values-fr then copy our string.xml into that and translate each entry. And this works based on the Phone Localization settings
I wanted to know if we can bypass the phone setting and and make the user select his required language inside the app?
My requirement is, i want to give a language selection option inside my app, and make the user select the language he wants for the app.. how to dynamically switch between the string.xml (for different languages) ???
thanks in advance
Create method which sets your basic Locale.Lets say
public static void setDefaultLocale(Context context,String locale) {
Locale locJa = new Locale(locale);
Locale.setDefault(locJa);
Configuration config = new Configuration();
config.locale = locJa;
context.getResources().updateConfiguration(config, context.getResources()
.getDisplayMetrics());
locJa = null;
config = null;
}
Now check when user selected Locale.(Here basically I have used menu for language selection).
Configuration config = new Configuration();
String newLocale = config.locale.getLanguage().substring(0, 2)
.toLowerCase();
if ("ja".equalsIgnoreCase(newLocale)) {
// Call above method with context & newLocale
}
// Sequentially you check for Locale & change that.
Check out this post... It is the same thing basically.
Changing Locale within the app itself
Locale appLoc = new Locale("en");
Locale.setDefault(appLoc);
Configuration appConfig = new Configuration();
appConfig.locale = appLoc;
getBaseContext().getResources().updateConfiguration(appConfig,
getBaseContext().getResources().getDisplayMetrics());
If you want to get images according their respective languages,You should create layout folder below like this.First i take the example for custom localization.
Locale appLoc = new Locale("xx");
Locale.setDefault(appLoc);
Configuration appConfig = new Configuration();
appConfig.locale = appLoc;
getBaseContext().getResources().updateConfiguration(appConfig,
getBaseContext().getResources().getDisplayMetrics());
Your layout folder should be layout-xx and your drawable folder also should be drawable-xx.But one thing that when you change the language,you have to refresh the layout.I used in my app, take a button and set the background image.But sometimes images are not changed so i have done like this .
btn.setBackgroundDrawable(null);
btn.setBackgroundResource(R.drwable.yourimage);
It is very easy just follow this link
languageToLoad = "hi"; // your language
locale = new Locale(languageToLoad);
Locale.setDefault(locale);
config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.activity_main);
- See more at: http://www.theappguruz.com/blog/multi-language-support-to-android-app#sthash.eGmzq57K.dpuf
Related
I have html and javascript that grabs a file and parses it and places chunks of the file in a textbox. However, the file has ANSI codes for colors. I want the textbox to display these colors as well. I have found ANSI4J but I don't know how to incorporate it into my code. There is a readme file and it posts the following:
var palette = new XtermPalette256();
AttributeConfig config = new DefaultTextAttributeConfig.Builder()
.defaultForegroundColor(0x000000)
.defaultBackgroundColor(0xffffff)
.fontFamilies(List.of("Arial", "'Times New Roman', Times, serif"))
.extraColorsEnabled(true)
.palette16(palette)
.palette256(palette)
.build();
//Now we need context that will keep attributes.
AttributeContext context = new DefaultAttributeContext(List.of(config));
//Now we create a function processor.
var processor = new DefaultCssFunctionProcessor.Builder()
.resolvers(new DefaultTextAttributeResolver())
.generators(new JavaFxCssGenerator())
.build();
...
//To generate CSS declarations we need to process function fragments. Currently only SGR functions are supported
Fragment fragment = ... ;
if (fragment.getType() == FragmentType.FUNCTION) {
FunctionFragment functionFragment = (FunctionFragment) fragment;
if (functionFragment.getFunction() == ControlSequenceFunction.SGR_SELECT_GRAPHIC_RENDITION) {
List<String> declarations = processor.process(functionFragment, context);
var style = String.join(";", declarations);
...
}
}
but I don't know what to do with this.
Any help would be appreciated.
Example: I want to get to get string "about_message" from "en"'s locale file (strings.xml) but currently using locale "de" inside the app and when referencing (R.string.about_message) returns the de string value obviously.
Is there a method to do this?
Let's assume you have a <string name="hello">Hello</string> inside your values/strings.xml, which also has a translation (say French) inside values-fr/strings.xml <string name="hello">Bonjour</string>. Normally you'd do the following:
String s = getResources.getString(R.string.hello); // s: "Hello"
To get the "Bonjor" string you'd have to create an alternative resources instance and use it to access the French string by changing to appropirate Locale:
Resources normalResources = getResources();
AssetManager assets = normalResources.getAssets();
DisplayMetrics metrics = normalResources.getDisplayMetrics();
Configuration config = new Configuration(standardResources.getConfiguration());
config.locale = Locale.FRENCH;
Resources frenchResources = new Resources(assets, metrics, config);
String s = defaultResources.getString(R.string.hello); // s: "Bonjour"
Hope this helps.
For example, I have a window with a preference button.
I want to make it so that when user press the preference button and checks his/her appropriate options and press ok, it saves the preference, then when user presses run on the main window, it runs accordingly to preference the user changed on the preference window.
Thank you in advance.
You can use java.util.prefs package. A simple example:
// Retrieve the user preference node for the package com.mycompany
Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class);
// Preference key name
final String PREF_NAME = "name_of_preference";
// Set the value of the preference
String newValue = "a string";
prefs.put(PREF_NAME, newValue);
// Get the value of the preference;
// default value is returned if the preference does not exist
String defaultValue = "default string";
String propertyValue = prefs.get(PREF_NAME, defaultValue); // "a string"
There are many more examples at java2s.com.
There is a Java Preferences API specifically for this purpose. It lets you store per-user preferences in an easy cross-platform way, while the API itself takes care of where and how to store the data.
public void saveProperties() {
try {
String USER_NAME = "Some name";
String DP_ADDRESS = "Some url";
//create a properties file
Properties props = new Properties();
props.setProperty("User name", USER_NAME);
props.setProperty("Display picture address", DP_ADDRESS);
File f = new File("YOUR_TARGET_FILE_PATH");
OutputStream out = new FileOutputStream( f );
//If you wish to make some comments
props.store(out, "User properties");
}
catch (Exception e ) {
e.printStackTrace();
}
}
You may use java.util.Properties to save your preferences
I'm looking for a bit of help on how to internationalize my hibernate validation messages while using GWT, so that it works with both client and server messages.
According to this question, I should put a ValidationMessages.properties file in my class path, or use the following code:
Validation
.byProvider(HibernateValidator.class)
.configure()
.messageInterpolator(
new ResourceBundleMessageInterpolator(
new PlatformResourceBundleLocator("com.mycompany.Messages")))
.buildValidatorFactory()
.getValidator();`
But will this method work on the client side, with GWT code? What should I do to make it work on the client side?
Please check GWT Internationalize.
If you want to internationlize for messages with GWT , check Static String Internationalization and Dynamic String Internationalization.I used GWT ConstantsWithLookup for constant datas (such as Text of Buttons , Text ofLabels ).
And I use GWT Messages for my message datas (such as alerts , warning , confirm , prompt dialogs).
Don't be forget to add configuration at gwt.xml file as below...
<extend-property name="locale" values="en"/>
<extend-property name="locale" values="ja"/>
<!-- set the fallback for locale default Japan -->
<set-property-fallback name="locale" value="ja"/>
........
I used Local en for English and ja for Japanese. I created ListBox for user to choose Locale as they prefer and used Cookie to maintain as user perference. Below is my sample codes for saving locale in cookie to internationalize at next-time open...
public static void initializeLocaleBox(final ListBox localeBox) {
String currentLocale = LocaleInfo.getCurrentLocale().getLocaleName();
if (currentLocale.equals("default")) {
currentLocale = "ja";
}
String[] localeNames = LocaleInfo.getAvailableLocaleNames();
for (String localeName : localeNames) {
if (!localeName.equals("default")) {
String nativeName = LocaleInfo.getLocaleNativeDisplayName(localeName);
localeBox.addItem(nativeName, localeName);
if (localeName.equals(currentLocale)) {
localeBox.setSelectedIndex(localeBox.getItemCount() - 1);
}
}
}
localeBox.addChangeHandler(new ChangeHandler() {
public void onChange(final ChangeEvent event) {
String localeName = localeBox.getValue(localeBox.getSelectedIndex());
Date now = new Date();
long sevenDays = now.getTime();
// seven days
sevenDays = sevenDays + (1000 * 60 * 60 * 24 * 7);
now.setTime(sevenDays);
Cookies.setCookie("locale", localeName, now);
UrlBuilder builder = Location.createUrlBuilder().setParameter("locale", localeName);
Window.Location.replace(builder.buildString());
}
});
}
public static boolean isLocaleJapan() {
String currentLocale = LocaleInfo.getCurrentLocale().getLocaleName();
return currentLocale != null && currentLocale.equals("ja") ? true : false;
}
public static boolean isLocaleEnglish() {
String currentLocale = LocaleInfo.getCurrentLocale().getLocaleName();
return currentLocale != null && currentLocale.equals("en") ? true : false;
}
For changing URL to localize , I converted with GWT as follow..
public static final String getBaseUrl(final int codesvrPort) {
String locale = Cookies.getCookie("locale");
if (locale == null || locale.equals("")) {
locale = "en";
}
String baseUrl = GWT.getHostPageBaseURL() + GWT.getModuleName() + ".html";
if (GWT.getHostPageBaseURL().contains("localhost")
|| GWT.getHostPageBaseURL().contains("127.0.0.1")) {
return baseUrl + "?locale=" + locale + "&gwt.codesvr=127.0.0.1:" + codesvrPort;
}
return "";
}
Here is useful link for you. I am sorry for too many links. Have some useful for you :)
Edit(Suffixing a properties file)
Qouted from this link.
Note: Suffixing a properties file
If you've never dealt with internationalization before, you may be wondering why the _de suffix is appended to German properties file. The suffix _de is the standard language tag for the German language (Deutsch). Languages tags are abbreviations that indicate a document or application's locale. In addition to specifying the language, they can also contain a subtag indicating the region of a locale. For example, the language tag for French-speaking Canada is fr_CA.
In GWT, properties files indicate the locale with a language code suffix (just like Java resource bundles). The exception is the properties file for the default locale. When no locale is explicitly set at runtime, the properties file with no language code suffix is used. For StockWatcher, you've specified the default translation with annotations instead of using a default properties file.
For example, I have a window with a preference button.
I want to make it so that when user press the preference button and checks his/her appropriate options and press ok, it saves the preference, then when user presses run on the main window, it runs accordingly to preference the user changed on the preference window.
Thank you in advance.
You can use java.util.prefs package. A simple example:
// Retrieve the user preference node for the package com.mycompany
Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class);
// Preference key name
final String PREF_NAME = "name_of_preference";
// Set the value of the preference
String newValue = "a string";
prefs.put(PREF_NAME, newValue);
// Get the value of the preference;
// default value is returned if the preference does not exist
String defaultValue = "default string";
String propertyValue = prefs.get(PREF_NAME, defaultValue); // "a string"
There are many more examples at java2s.com.
There is a Java Preferences API specifically for this purpose. It lets you store per-user preferences in an easy cross-platform way, while the API itself takes care of where and how to store the data.
public void saveProperties() {
try {
String USER_NAME = "Some name";
String DP_ADDRESS = "Some url";
//create a properties file
Properties props = new Properties();
props.setProperty("User name", USER_NAME);
props.setProperty("Display picture address", DP_ADDRESS);
File f = new File("YOUR_TARGET_FILE_PATH");
OutputStream out = new FileOutputStream( f );
//If you wish to make some comments
props.store(out, "User properties");
}
catch (Exception e ) {
e.printStackTrace();
}
}
You may use java.util.Properties to save your preferences