How to change the language of the dynamic content in android - java

I have to do this:
user should be able to enter text to create post - "create a post " button
these post should be viewed in a wall.
Based on chosen languages, static contents as well as dynamic contents on the app should change accordingly. It should be available in the settings screen of the app.
I have a problem that how to change the language of the content view on MainActivity

You can change static content like this.
First create string file based on the language.
when change language execute this method
public void changeLang(String lang)
{
myLocale = new Locale(lang);
saveLocale(lang);
Locale.setDefault(myLocale);
android.content.res.Configuration config = new android.content.res.Configuration();
config.locale = myLocale;
getActivity().getApplicationContext().getResources().updateConfiguration(config, null);
//getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
updateTexts();
}
private void updateTexts()
{
//update text of label in here.
textLabel.setText(R.string.welcome);
}
next overide the configuration change method
#Override
public void onConfigurationChanged(android.content.res.Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (myLocale != null){
newConfig.locale = myLocale;
Locale.setDefault(myLocale);
getActivity().getBaseContext().getResources().updateConfiguration(newConfig, getActivity().getBaseContext().getResources().getDisplayMetrics());
}
}
I have no idea about dynamic content. I think it will not be possible. But if you have content with other langage you can load that when change language.

Related

How to get JavaFx TabPane title to be WebView's site title?

I am using JavaFx, and have Tabs with WebView objects on them. I am trying to have my tab title's text to read the web page's title like in most web browsers. When I use the "getTitle" method I get an empty title, Which I assume is because the page hasn't loaded yet. All the research I've done gives me an Android Solution and I'm looking for something that works with a desktop application. Here's what I have.
public class WebsiteTab extends Tab {
final static String DEFAULT_SITE = "https://google.com";
VBox browserBox;
WebView webView;
public WebsiteTab() {
super("Site One");
webView = new WebView();
webView.setPrefHeight(5000);
goToSite(DEFAULT_SITE);
browserBox = new VBox(10,webView);
VBox.setVgrow(browserBox, Priority.ALWAYS);
setContent(browserBox);
}
public void goToSite(final String site) {
webView.getEngine().load(site);
setText(webView.getEngine().getTitle());
}
}
Any help would be appreciated.
You can bind the tab's text property to the web engine's title property.
public class WebsiteTab extends Tab {
final static String DEFAULT_SITE = "https://google.com";
VBox browserBox;
WebView webView;
public WebsiteTab() {
super("Site One");
webView = new WebView();
webView.setPrefHeight(5000);
textProperty().bind(webView.getEngine().titleProperty()); // bind the properties
goToSite(DEFAULT_SITE);
browserBox = new VBox(10,webView);
VBox.setVgrow(browserBox, Priority.ALWAYS);
setContent(browserBox);
}
public void goToSite(final String site) {
webView.getEngine().load(site);
}
}
This will cause the text property to always have the same value as the title property. In other words, when the title property's value changes the text property will be automatically updated. Notice I bind the properties in the constructor as you only need to create the binding once. Also note that while bound you can no longer manually set the text property; attempting to do so will cause an exception to be thrown. For more information, see Using JavaFX Properties and Binding.

onCreate is ran twice because I set locale at app launch?

I have been wondering for a while why my onCreate method is run twice and have now found out that it has to do with me setting the locale of the app at launch... My question is, is it necessary for it to run twice or not?
This is the code that makes onCreate run twice:
/*Sets the language of the application and also returns the integer value of selected language*/
protected Integer setLanguage() {
String lang = prefs.getString("language-key","0");
Integer language = Integer.parseInt(lang);
Configuration config = context.getResources().getConfiguration();
if (!decideLang(language).equals("") && !config.locale.getLanguage().equals(decideLang(language))) {
setLocale(decideLang(language));
}
return language;
}
/*Sets the locale*/
private void setLocale(String lang) {
((Activity) context).recreate();
Locale myLocale = new Locale(lang);
Resources res = context.getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
}
The integer that the setLanguage method returns is later used to determine what URL to use in a later stage but I have come to realize that is not important for my question.
My question is, WHY does onCreate need to run twice because of this code?
((Activity) context).recreate();, as it states on the tin, recreates the Activity, so onCreate() is, of course, going to be called twice.
(From comments)

Handling positions in FirebaseRecyclerAdapter

I have fiddled with the FirebaseRecyclerAdapter for quite some time now. It's really a great tool to populate a custom list/recycler view very fast with all of its features. However, one thing that I would like to ask is how to handle positions of items inside the adapter itself.
So for example, I want to mimic this small feature that WhatsApp has in their chats.
So, in a group chat setting, if a person sends more than one consecutive message in a row, the display name of that particular person will be invisible.
The logic behind it according to my understanding: if the person who sends the message is the same for (position - 1), then I will just make the EditText invisible for (position). This is, of course, to prevent a very long stream of text with minimum amounts of repetitive information.
Let's say the JSON tree from Firebase database is as follows.
{
"messages" : {
"pushed_id_1" : {
"message_sender" : "AppleJuice",
"message_text" : "Are you free?"
},
"pushed_id_2" : {
"message_sender" : "AppleJuice",
"message_text" : "On Saturday I mean..."
}
}
}
The FirebaseRecyclerAdapter would look like this.
FirebaseRecyclerAdapter<Message, MessageViewHolder> adapter = new FirebaseRecyclerAdapter<Message, MessageViewHolder>(Message.class, R.layout.message_item, MessageViewHolder.class, myRef) {
#Override
protected void populateViewHolder(MyBookingsViewHolder viewHolder, Booking model, int position) {
viewHolder.messageSender.setText(model.getMessage_sender());
viewHolder.messageText.setText(model.getMessage_text());
//put some code here to implement the feature that we need
}
};
messages_recycler_menu.setAdapter(adapter);
The furthest I have gone is to use getItemCount() method in the FirebaseRecyclerAdapter, but I am still unable to achieve the feature that mimics that of Whatsapp's that I was talking about previously.
Is there a method that can achieve this? Or am I missing something very important in this example?
String lastSender=null; //or some random string
FirebaseRecyclerAdapter<Message, MessageViewHolder> adapter =
new FirebaseRecyclerAdapter<Message, MessageViewHolder>
(Message.class, R.layout.message_item, MessageViewHolder.class, myRef) {
#Override
protected void populateViewHolder(MyBookingsViewHolder viewHolder, Booking model, int position) {
if (model.getMessage_sender().equals(lastSender){ //check if the current sender is same as the last sender
viewHolder.messageText.setText(model.getMessage_text()); //setting only message text
viewHolder.messageSender.setVisibility(View.GONE); //if required
}else{
lastSender=model.getMessage_sender();//updating the lastSender value
viewHolder.messageSender.setVisibility(View.VISIBLE); //if required
viewHolder.messageSender.setText(model.getMessage_sender());
viewHolder.messageText.setText(model.getMessage_text());
}
//put some code here to implement the feature that we need
}
};
messages_recycler_menu.setAdapter(adapter);
As discussed in comments:
Let's suppose I received message and stored sender's name in constant String that should be static constant in some class i.e. AppConstants so that It can be accessed everywhere therefore after that:
in populateViewHolder or in your message receiver do something like this:
if (TextUtils.isEqual(storedSender,model.getMessage_sender())){
viewHolder.messageSender.setVisiblity(View.GONE)
}
else{
// do your normal flow
viewHolder.messageSender.setVisiblity(View.VISIBLE);
storedSender = model.getMessage_sender();
}
In this way automatically the last message's sender's name will be updated , this is exactly what you were trying to achieve by adapter position!

implement Undo Redo in form based editor

I am developing a multipage Form Editor to edit/create a customized XML file in Eclipse.
structure is looks like:
Implementation class is MyXMLFormEditor which extends FormEditor.
Each page of FormEditor extends FormPage (i.e. MyXMLFormPage extends FormPage).
Between FormEditor and actual XML file I am maintaining JDOM model.
Also I implemented dirty flag handling. So user’s inputs into form editor gets saved into JDOM till the time user presses Save button. When user presses save button JDOM is written/serialized into XML file.
In an editor with above functionality I would like to implement undo/redo functionality as follow:
When editor is dirty (user changed something into form editor and it is not saved) undo operation should revert back the changes in form editor as well as JDOM to its original state (i.e. the state when editor was non-dirty) and redo operation should again bring back the changes into FormEditor as well as JDOM and editor should become dirty.
Following is my code snippet
MyXMLFormEditor.java
public class MyXMLFormEditor extends FormEditor {
MyXMLFormEditor(){
super();
}
#Override
protected FormToolkit createToolkit(Display display) {
// Create a toolkit that shares colors between editors.
return new FormToolkit(Activator.getDefault().getFormColors(display));
}
#Override
public void init(IEditorSite site, IEditorInput editorInput) {
setSite(site);
mSite = site;
setInput(editorInput);
try {
super.init(site, editorInput);
} catch (PartInitException e1) {
e1.printStackTrace();
}
if (!(editorInput instanceof IFileEditorInput))
try {
throw new PartInitException("Invalid Input: Must be IFileEditorInput");
} catch (PartInitException e) {
e.printStackTrace();
}
setPartName(fileName);
}
public void setUpProgFile(IEditorSite site, IEditorInput editorInput){
IFileEditorInput fileInput = ((IFileEditorInput) editorInput);
//create document builder and prepare JDom model for xml file.
}
#Override
protected void addPages() {
try {
//add 'Main' page
objMyXMLFormPage = new MyXMLFormPage (this, "FirstPage","Main");
//set rootNode of MyXMLFormPage
objMyXMLFormPage.rootNode = getRootNode();
objMyXMLFormPage.filePath = filePath;
objMyXMLFormPage.document = document;
addPage(objMyXMLFormPage);
} catch (PartInitException e) {
e.printStackTrace();
}
}
#Override
public void doSave(IProgressMonitor monitor) {
System.out.println("MyXMLFormEditor: doSave");
//logic to write jdom contents into xml file.
objMyXMLFormPage.setDirty(false);
}
#Override
public void doSaveAs() {
System.out.println("MyXMLFormEditor: doSaveAs");
}
#Override
public boolean isSaveAsAllowed() {
System.out.println("MyXMLFormEditor: isSaveAsAllowed");
return true;
}
}
MyXMLFormPage .java
public class MyXMLFormPage extends FormPage{
//private members declaration.
public MyXMLFormPage (MyXMLFormEditor editor,String title, String id) {
// initialize the editor and set its title and name.
super(editor,title,id );
}
#Override
public void createFormContent(IManagedForm managedForm) {
// Set page title
super.createFormContent(managedForm);
FormToolkit mMyXMLFormPage Toolkit = managedForm.getToolkit();
//Logic to creat UI and populating its contents from JDom
}
private void makeEditorDirty() {
updateJdom = true;
setDirty(true);
}
private void updateJDom() {
if(updateJdom){
System.out.println("*** Jdom updated ***");
updateJdom = false;
}
}
#Override
public boolean isDirty() {
return isDirtyFlag;
}
protected void setDirty(boolean value) {
isDirtyFlag = value;
dirtyStateChanged();
}
public void dirtyStateChanged() {
getEditor().editorDirtyStateChanged();
}
#Override
public boolean isSaveAsAllowed() {
System.out.println("MyXMLFormPage .isSaveAsAllowed");
return false;
}
#Override
public void doSave(IProgressMonitor monitor) {
System.out.println("MyXMLFormPage .doSave");
}
}
Can anyone provide me pointer/samples on how to implement undo/redo functionality into FormEditor? It would be good if the approach make use of existing undo/redo framework of Eclipse PDE or workbench.
There are a couple of important points to make about the pattern used by multi-page editor implementations in Eclipse. There may be other ways of doing it, but the editors in Eclipse seem to adhere to these points:
Maintain a model of the data that's shared by the pages in the editor (you're doing this).
Only refresh a page with the model data when the page is about to be displayed. Don't try to keep non-displayed pages in sync with the model.
When you perform an undo or redo, make the appropriate changes to the model (per #Scorpion's comment) and then refresh the current page.
Each page should have a its-ok-to-leave-this-page method (I don't remember the name) which is called to make sure that the displayed data is error free enough to allow the page to be changed (you don't want errors on non-displayed data).
Pages have an about-to-leave-this-page method which is called to save any changes to the model before switching pages. Most pages don't do anything here because the model is modified sometimes by every keystroke, but the source page would use this method to replace the model completely with the parse results on the text editor contents.
What this means is that your forms don't have to perform the undo/redo themselves. Rather, the classes representing the multipage editor pages will interact with the model as it's changed and then pass the correct data to be displayed to the forms.
The forms will need to listen for the undo/redo key events and pass those along to the model via the command pattern.

java gwt richtextarea change font-family

The Object richtextarea of java gwt has as default the font-family 'times new roman' is it somehow possible to change the family to 'Arial'?
You have several options. You can create a CSS class and set it on the body element of the document inside RichTextArea, or you can set the style attribute on it directly. If you want this change to be consistent throughout your app, I recommend creating a new class and adding an InitializeHandler to it.
public class MyRichTextArea extends RichTextArea {
public MyRichTextArea() {
addInitializeHandler(new InitializeHandler() {
#Override
public void onInitialize(InitializeEvent ie) {
Document document = IFrameElement.as(getElement()).getContentDocument();
BodyElement body = document.getBody();
body.setAttribute("style", "font-family: Arial Unicode MS,Arial,sans-serif;");
});
}
}
}
It is better to use the provided functionality.
If you want to change it at creation time, you will need the initializeHandler as mentioned in answer 1:
RichTextArea rta = new RichTextArea();
rta.addInitializeHandler(new InitializeHandler() {
public void onInitialize(InitializeEvent event) {
rta.getFormatter().setFontName("\"Trebuchet MS\",Trebuchet,Arial");
rta.getFormatter().setFontSize(FontSize.SMALL);
rta.getFormatter().setForeColor("#FF0000");
}
});
PS: you need to do this before you add any content to the textarea, or it will only be applied to new input.
I've found more common solution:
addInitializeHandler(new InitializeHandler() {
public void onInitialize(InitializeEvent ie) {
Document document = IFrameElement.as(getElement()).getContentDocument();
BodyElement body = document.getBody();
HeadElement head = HeadElement.as(Element.as(body.getPreviousSibling()));
LinkElement styleLink = document.createLinkElement();
styleLink.setType("text/css");
styleLink.setRel("stylesheet");
styleLink.setHref("richtextarea.css");
head.appendChild(styleLink);
}
});
After adding initialization handler, it's easy to change styles in richtextarea.css file

Categories

Resources