This question already has answers here:
Change app language programmatically in Android
(34 answers)
Closed 6 years ago.
I need to switch between two languages inside the android application itself.
Now, I have string values for two different languages in two strings.xml files in two different folders, one is under Values folder(by default) and another one is under values-fr(for french) which is created when tried Edit translation under language in android studio.But I don't know how to switch between the languages.
It shows the default language (i.e., English) but don't know how to implement a way to switch to other language.
Does any one have easy way of implementing it...?
You can use Android-LocalizationActivity
Here an excerpt from the documentation:
Keep calm and stay easy with multiple language supported in your
android application.
It's basic for android application to be supported multiple languages.
Yeah! It's very easy because android has String Resource. Developer
just had to prepare the text for different languages then android
system will use itself. But frequently problem is "On-time Language
Changing". Because the String Resource was designed to be depending on
current device language. but if we want to change the language by
click some button. It will be difficult to handle it. This problem
will solved because I have created a new library to handle application
language. It called "Localization Activity" library.
Here the example to use it from the documentation:
import android.os.Bundle;
import android.view.View;
import com.akexorcist.localizationactivity.LocalizationActivity;
public class MainActivity extends LocalizationActivity implements View.OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple);
findViewById(R.id.btn_th).setOnClickListener(this);
findViewById(R.id.btn_en).setOnClickListener(this);
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.btn_en) {
setLanguage("en");
} else if (id == R.id.btn_th) {
setLanguage("th");
}
}
}
In the example above, when user click on a button. It will change to English or Thai language.
You can use the locale class to do this .Hope this helps
public class LocaleLanguage {
private static Locale mLocale;
public static void setLocale(Locale locale) {
mLocale = locale;
if(mLocale != null) {
Locale.setDefault(mLocale);
}
}
public static void updateConfig(ContextThemeWrapper wrapper) {
if(mLocale != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
Configuration configuration = new Configuration();
configuration.setLocale(mLocale);
wrapper.applyOverrideConfiguration(configuration);
}
}
public static void updateConfig(Application app, Configuration configuration) {
if(mLocale != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
//Wrapping the configuration to avoid Activity endless loop
Configuration config = new Configuration(configuration);
config.locale = mLocale;
Resources res = app.getBaseContext().getResources();
res.updateConfiguration(config, res.getDisplayMetrics());
}
}
}
here is the application class
public class App extends Application {
public void onCreate(){
super.onCreate();
// get user preferred language set locale accordingly new locale(language,country)
LocaleUtils.setLocale(new Locale("iw"));
LocaleUtils.updateConfig(this, getBaseContext().getResources().getConfiguration());
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
LocaleUtils.updateConfig(this, newConfig);
}
}
here is the your activity
public class MainActivity extends Activity {
public BaseActivity() {
LocaleUtils.updateConfig(this);
}
}
And for more refer this link for whole tutorial refer this link
Related
I want to use this Calendar view in my android java app.
https://github.com/kizitonwose/CalendarView
I've tried myself first before coming here but I could not implement this in java as documentation is for Kotlin.
Someone please help me, I am stuck on step 2.
Step 2:
Kotlin Code of Documentation:
class DayViewContainer(view: View) : ViewContainer(view) {
val textView = view.calendarDayText
}
My Java Equivalent Code:
class DayViewContainer extends ViewContainer {
public DayViewContainer(View view) {
super(view);
final TextView calendar_day_text = view.findViewById(R.id.calendarDayText);
}
}
Kotlin Code of Documentation:
calendarView.dayBinder = object : DayBinder<DayViewContainer> {
// Called only when a new container is needed.
override fun create(view: View) = DayViewContainer(view)
// Called every time we need to reuse a container.
override fun bind(container: DayViewContainer, day: CalendarDay) {
container.textView.text = day.date.dayOfMonth.toString()
}
}
My Java Equivalent Code:
calendarView.setDayBinder(new DayBinder<DayViewContainer>(){
#Override
public DayViewContainer create(View view) {
return new DayViewContainer(view);
}
#Override
public void bind(DayViewContainer dayViewContainer, CalendarDay calendarDay) {
TextView textView =
dayViewContainer.getView().findViewById(R.id.calendarDayText);
textView.setText(calendarDay.getDate().getDayOfMonth());
}
});
DayViewContainer should make the TextView a member variable so you can actually access it. You could make a getter for it, but for simple classes like this my personal preference is to make fields public final to simplify it.
class DayViewContainer extends ViewContainer {
public final TextView calendarDayText;
public DayViewContainer(View view) {
super(view);
calendarDayText = view.findViewById(R.id.calendarDayText);
}
}
And since you're calling your own Java code, and we made this member field public, you don't need to call a getter for it in your DayBinder:
#Override
public void bind(DayViewContainer dayViewContainer, CalendarDay calendarDay) {
dayViewContainer.calendarDayText.setText(calendarDay.getDate().getDayOfMonth());
}
Thank you guys for showing some concern here.
I figured it out.
The mistake was that I was not converting integer days to String to use it as text on TextView.
The correction is here in following line:
textView.setText(Integer.toString(calendarDay.getDate().getDayOfMonth()));
This question already has answers here:
How can one detect airplane mode on Android?
(13 answers)
Closed 7 years ago.
I am working on developing an Android app that will detect airplane mode throughout whole application. where to i add this code?
#SuppressWarnings("deprecation")
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static boolean isAirplaneModeOn(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
} else {
return Settings.Global.getInt(context.getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
}
}
You can add this code where you want to detect whether connection is available.
for example:
#Override
public void onClick(View v) {
boolean isonair = myApp.isAirplaneModeOn(this);
Toast.makeText(this, "IS on AIR? " + isonair, Toast.LENGTH_LONG).show();
}
If you want to have an access for static function use them in Application class:
public class myApp extends Application {
public static function isAirplaneModeOn() {
...
}
}
in any activity use this access: myApp.isAirplaneModeOn()
do not forget update your AndroidManifest.xml:
<application
android:largeHeap="true"
android:name=".myApp" <<<<<<<<<<<<<<<<<<< this is your class name
android:icon="#drawable/somedrawable"
android:label="#string/app_alias"
android:theme="#style/AppTheme" >
Create a Interface like AirplaneModeManager whose Implementation extending broadcast receiver to get notified in the scenario when airplane mode is activated
you can use this code in Implementation to keep a track and use its methods in whole application to get the status !!
Does someone knows if it is possible to add push notifications(like Amazon Simple Notification Service) in an Android and iOS with RoboVM libGDX projects? And if it is possible, are there any good tutorials or good hints how to implement such things?
I would be happy about every hint how I can implement it.
Hi I know this is an old question but I was struggling to find a solution for this specially for iOS, but I finally found a way. If the explanation below is confusing and you prefer to see an example here is a github repo with a sample project:
Repo GitHub
I only show the code for iOS see the repo for Android.
The idea is simple you need to create a class that handles sending a notification for each platform on each of your projects (Android and iOS) and have it implement an interface called NotificationsHandler.
NotificationsHandler:
public interface NotificationsHandler {
public void showNotification(String title, String text);
}
iOS Adapter:
public class AdapteriOS implements NotificationsHandler {
public AdapteriOS () {
//Registers notifications, it will ask user if ok to receive notifications from this app, if user selects no then no notifications will be received
UIApplication.getSharedApplication().registerUserNotificationSettings(UIUserNotificationSettings.create(UIUserNotificationType.Alert, null));
UIApplication.getSharedApplication().registerUserNotificationSettings(UIUserNotificationSettings.create(UIUserNotificationType.Sound, null));
UIApplication.getSharedApplication().registerUserNotificationSettings(UIUserNotificationSettings.create(UIUserNotificationType.Badge, null));
//Removes notifications indicator in app icon, you can do this in a different way
UIApplication.getSharedApplication().setApplicationIconBadgeNumber(0);
UIApplication.getSharedApplication().cancelAllLocalNotifications();
}
#Override
public void showNotification(final String title, final String text) {
NSOperationQueue.getMainQueue().addOperation(new Runnable() {
#Override
public void run() {
NSDate date = new NSDate();
//5 seconds from now
NSDate secondsMore = date.newDateByAddingTimeInterval(5);
UILocalNotification localNotification = new UILocalNotification();
localNotification.setFireDate(secondsMore);
localNotification.setAlertBody(title);
localNotification.setAlertAction(text);
localNotification.setTimeZone(NSTimeZone.getDefaultTimeZone());
localNotification.setApplicationIconBadgeNumber(UIApplication.getSharedApplication().getApplicationIconBadgeNumber() + 1);
UIApplication.getSharedApplication().scheduleLocalNotification(localNotification);
}
});
}
}
Now by default Libgdx passes your ApplicationListener or Game object to AndroidLauncher and IOSLauncher along with a configuration object. The trick is to pass the class we created earlier to the ApplicationListener so that you can use it inside your Core project. Simple enough:
public class IOSLauncher extends IOSApplication.Delegate {
#Override
protected IOSApplication createApplication() {
IOSApplicationConfiguration config = new IOSApplicationConfiguration();
// This is your ApplicationListener or Game class
// it will be called differently depending on what you
// set up when you created the libgdx project
MainGame game = new MainGame();
// We instantiate the iOS Adapter
AdapteriOS adapter = new AdapteriOS();
// We set the handler, you must create this method in your class
game.setNotificationHandler(adapter);
return new IOSApplication(game, config);
}
public static void main(String[] argv) {
NSAutoreleasePool pool = new NSAutoreleasePool();
UIApplication.main(argv, null, IOSLauncher.class);
pool.close();
}
}
Now that you have a reference to the implementation of NotificationHandler you can simply call it through your Core project.
public class MainGame extends Game {
// This is the notificatino handler
public NotificationHandler notificationHandler;
#Override
public void create () {
// Do whatever you do when your game is created
// ...
}
#Override
public void render () {
super.render();
// This is just an example but you
// can now send notifications in your project
if(condition)
notificationHandler.showNotification("Title", "Content");
}
#Override
public void dispose() {
super.dispose();
}
// This is the method we created to set the notifications handler
public void setNotificationHandler(NotificationHandler handler) {
this.notificationHandler = handler;
}
}
One last thing
If you need to run the Desktop version then you will need to do the same thing for Desktop otherwise you might get errors, it will not do anything on the Desktop, or you can check the platform before calling the method showNotfication. You can clone the repo where I do this:
Repo GitHub
I've never done it myself. But you can use this tutorial to find out how to write Android specific code in your libGDX project. Your Android code could then receive the notifications and trigger a callback in libGDX. I hope this is at least a step in the right direction.
However I' not sure about doing the same for iOS.
I want to receive notifications for onTrimMemory when available (ICS+) and onLowMemory otherwise (> ICS). My questions are the following:
Will the system allow me to define a class that implements an interface that is not in the current SDK as long as I don't instantiate it? For example, defining CallbacksICS implements ComponentCallbacks2 while targeting minSdk 8, for example, but checking the current SDK_INT before choosing what to instantiate and register.
Will onTerminate always get called when the application is ready to be cleaned up by the system? I vaguely remember hearing in the early days that some of the Application life cycle methods aren't guaranteed to be called.
From my Application class:
#SuppressLint("NewApi")
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
callbacksICS = new CallbacksICS();
registerComponentCallbacks(callbacksICS);
}
else {
callbacksLegacy = new CallbacksLegacy();
registerComponentCallbacks(callbacksLegacy);
}
}
#SuppressLint("NewApi")
#Override
public void onTerminate() {
super.onTerminate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
unregisterComponentCallbacks(callbacksICS);
}
else {
unregisterComponentCallbacks(callbacksLegacy);
}
}
Sorry if this was already answered before. I did a little searching and found nothing that could solve my problem. I created an application with Spring Roo, then converted to a GWT app.
All the code generated by Spring Roo is only for CRUD. Now i want to add a Calendar for make appointments, so i need to move to another page.
I´ve added this code to
ScaffoldDesktopShell.java()
public ScaffoldDesktopShell() {
initWidget(BINDER.createAndBindUi(this));
startButton.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
RootLayoutPanel.get().add(new NovoPainel());
}
});
}
...
Then created a new UIbinder, called it NovoPainel() and added this code:
public NovoPainel() {
initWidget(uiBinder.createAndBindUi(this));
botao.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
RootLayoutPanel.get().clear();
RootLayoutPanel.get().add (new ScaffoldDesktopShell());
}
});
}
Everything goes fine moving from my root panel to NovoPainel, but when i need to go back to rootPanel the page doesn´t render correctly.
EX: Doesn´t show ** ValuePicker ** to click on left panel and render on center.
This is my RootPanel
and this image is when navigate from rootPanel to NovoPainel
and finally this one is returning from NovoPainel to RootPanel
You have to integrate with Roo generated architecture so that you can still benefit from Roo scaffolding.
Roo generated code hides most of behavior in _Roo_Gwt classes and it is because GWT doesn’t currently support ITDs. So changes have to be made in derived classes by overriding methods from _Roo_Gwt class.
To navigate application use Places, ActivityMapper and ActivitiManager (you can find good read on #Thomas Broyer posterous and GWT help).
If you take a look in ScaffoldDesktopShell.ui.xml - page is devided in three main areas.
ApplicationMasterActivities class is responsible for master area.
masterActivityManager.setDisplay(shell.getMasterPanel());
proxyListPlacePicker in ScaffoldDesktopApp.init() generates place change event with apropriate ProxyListPlace.
public void onValueChange(ValueChangeEvent<ProxyListPlace> event) {
placeController.goTo(event.getValue());
}
ApplicationMasterActivities class creates appropriate Activity in Master area by checking EntityProxy type contained in ProxyListPlace object.
public Activity getActivity(Place place) {
if (!(place instanceof ProxyListPlace)) {
return null;
}
ProxyListPlace listPlace = (ProxyListPlace) place;
return new ApplicationEntityTypesProcessor<Activity>() {
#Override
public void handlePet(PetProxy isNull) {
setResult(new PetListActivity(requests, ScaffoldApp.isMobile() ? PetMobileListView.instance() : PetListView.instance(), placeController));
}
#Override
public void handleOwner(OwnerProxy isNull) {
setResult(new OwnerListActivity(requests, ScaffoldApp.isMobile() ? OwnerMobileListView.instance() : OwnerListView.instance(), placeController));
}
}.process(listPlace.getProxyClass());
}
Navigation is created by listing all EntityProxy's in ScaffoldApp class
protected HashSet<ProxyListPlace> getTopPlaces() {
Set<Class<? extends EntityProxy>> types = ApplicationEntityTypesProcessor.getAll();
HashSet<ProxyListPlace> rtn = new HashSet<ProxyListPlace>(types.size());
for (Class<? extends EntityProxy> type : types) {
rtn.add(new ProxyListPlace(type));
}
return rtn;
}
To output meaningfull name in navigation menu they are rendered using ApplicationListPlaceRenderer
public String render(ProxyListPlace object) {
return new ApplicationEntityTypesProcessor<String>() {
#Override
public void handlePet(PetProxy isNull) {
setResult("Pets");
}
#Override
public void handleOwner(OwnerProxy isNull) {
setResult("Owners");
}
}.process(object.getProxyClass());
}
So you have to create new Activity.
public class SomeActivity extends Composite implements Activity{
private static SomeActivityUiBinder uiBinder = GWT
.create(SomeActivityUiBinder.class);
interface SomeActivityUiBinder extends UiBinder<Widget, SomeActivity> {
}
private AcceptsOneWidget display;
public SomeActivity() {
initWidget(uiBinder.createAndBindUi(this));
}
#Override
public String mayStop() {
return null;
}
#Override
public void onCancel() {
onStop();
}
#Override
public void onStop() {
this.display.setWidget(null);
}
#Override
public void start(AcceptsOneWidget panel, EventBus eventBus) {
this.display = panel;
this.display.setWidget(this);
}
}
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder" xmlns:g="urn:import:com.google.gwt.user.client.ui">
<g:HTMLPanel>
Hello world!
</g:HTMLPanel>
</ui:UiBinder>
Create appropriate EntityProxy. It is only to obey ProxyListPlace mechanism.
public interface SomeEntityProxy extends EntityProxy {
}
Create SomeActivity in A
#Override
public Activity getActivity(Place place) {
if (!(place instanceof ProxyListPlace)) {
return null;
}
Activity activity = super.getActivity(place);
if (activity == null) {
ProxyListPlace listPlace = (ProxyListPlace) place;
if (SomeEntityProxy.class.equals(listPlace.getProxyClass())) {
activity = new SomeActivity();
}
}
return activity;
}
Add place to navigation in ScaffoldApp or override getTopPlaces in derived class.
rtn.add(new ProxyListPlace(SomeEntityProxy.class));
Set correct menu rendering text in ApplicationListPlaceRenderer
#Override
public String render(ProxyListPlace object) {
String label = super.render(object);
if(label == null) {
if (SomeEntityProxy.class.equals(object.getProxyClass())) {
label = "Some activity";
}
}
return label;
}
Code in GitHub.
GWT 2.1 introduced new classes that implements the Model-View-Places pattern (MVP). This pattern (and the GWT 2.1 concepts) are heavily based on best practices from developers who have build scalable GWT-based applications, so many people are migrating in this direction.
Roo generates a GWT 2.1 application; all of its navigational code is built on top of Activities and Places. The reason I bring this up is it sounds like you are attempting to side-step a lot of this navigational framework to implement your own. I'm not sure, but I believe your problem is coming from the fact that the MVP code is getting confused as a result.
My recommendation would be to work through the GWT MVP article linked above first. Do it completely separate of Roo, because the application that Roo generates is more complex. Once you have a good handle on it, go back through the Roo-generated application and it will likely make more sense.
You can create two div tags in your Porject.html file respectively with id firstdivtag_id1 and seconddivtag_id2.
Display first page by using
RootPanel.get("firstdivtag_id1").add(Panel1);
And then to switch over to another panel use
RootPanel.get("seconddivtag_id2").add(Panel2);