I found many ways to change the activities theme dynamically.
But I use some chart and graph from aChartengine that can't change their theme, because they are not just like activities.
So, I need to find out a way to change app theme dynamically so that also my charts theme will change too!
I wonder if someone can solve this problem.
This is my code, which works on each activity:
public class Utils
{
private static int sTheme;
public final static int THEME_DEFAULT = 0;
public final static int THEME_WHITE = 1;
public final static int THEME_BLUE = 2;
public final static int THEME_PINK = 3;
/**
* Set the theme of the Activity, and restart it by creating a new Activity
* of the same type.
*/
public static void changeToTheme(Activity activity, int theme)
{
sTheme = theme;
activity.finish();
activity.startActivity(new Intent(activity, activity.getClass()));
}
/** Set the theme of the activity, according to the configuration. */
public static void onActivityCreateSetTheme(Activity activity)
{
switch (sTheme)
{
default:
case THEME_DEFAULT:
break;
case THEME_WHITE:
activity.setTheme(R.style.Theme_white);
break;
case THEME_BLUE:
Log.i("THM", "blue intered in utils");
activity.setTheme(R.style.Theme_blue);
break;
case THEME_PINK:
activity.setTheme(R.style.Theme_pink);
break;
}
}
}
And I use this code to change my activity theme:
Utils.changeToTheme(G.tabActivity, Utils.THEME_DEFAULT);
You can store your current theme in SharedPreferences and apply it on start of your app:
SharedPreferences pref = context.getSharedPreferences("your_pref_name", android.content.Context.MODE_PRIVATE);
String theme = pref.getString("your_pref_key", "your_default_theme");
context.setTheme(theme);
Then, when you change your theme you should restart application:
Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
finish();
startActivity(intent);
Related
This question is a follow up to this problem here: How to make retrofit API call using ViewModel and LiveData
The mistakes 1 and 2 highlighted in that post's response have been fixed. For mistake 3, I haven't yet moved the API call to a repository, but I will once the code start working properly.
So I'm trying to make an API call using Retrofit, using MVVM with LiveData and ViewModel. The API call (which currently is in the ViewModel), is working properly, but the changes is not being picked up by the Observer in the Activity.
I've setup my ViewModel observer as follow:
public class PopularGamesActivity extends AppCompatActivity {
private static final String igdbBaseUrl = "https://api-endpoint.igdb.com/";
private static final String FIELDS = "id,name,genres,cover,popularity";
private static final String ORDER = "popularity:desc";
private static final int LIMIT = 30;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_popular_games);
PopularGamesViewModel popViewModel = ViewModelProviders.of(this).get(PopularGamesViewModel.class);
popViewModel.getGameList().observe(this, new Observer<List<Game>>() {
#Override
public void onChanged(#Nullable List<Game> gameList) {
String firstName = gameList.get(0).getName();
Timber.d(firstName);
}
And my ViewModel code is as follow:
public class PopularGamesViewModel extends AndroidViewModel {
private static final String igdbBaseUrl = "https://api-endpoint.igdb.com/";
private static final String FIELDS = "id,name,genres,cover,popularity";
private static final String ORDER = "popularity:desc";
private static final int LIMIT = 30;
public PopularGamesViewModel(#NonNull Application application) {
super(application);
}
public LiveData<List<Game>> getGameList() {
final MutableLiveData<List<Game>> gameList = new MutableLiveData<>();
// Create the retrofit builder
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(igdbBaseUrl)
.addConverterFactory(GsonConverterFactory.create());
// Build retrofit
Retrofit retrofit = builder.build();
// Create the retrofit client
RetrofitClient client = retrofit.create(RetrofitClient.class);
Call<List<Game>> call = client.getGame(FIELDS,
ORDER,
LIMIT);
call.enqueue(new Callback<List<Game>>() {
#Override
public void onResponse(Call<List<Game>> call, Response<List<Game>> response) {
Timber.d("api call sucesss");
if (response.body() != null) {
Timber.d("First game: " + response.body().get(0).getName());
gameList.setValue(response.body());
}
}
#Override
public void onFailure(Call<List<Game>> call, Throwable t) {
Timber.d("api call failed");
}
});
return gameList;
}
}
When I run the code, the onResponse in the ViewModel class will output the correct response from the API call, so the call is working properly. But the onChanged() in the PopularGamesActivity class will never get called. Can someone shed some light on what I'm doing wrong? Thank you!
Ok, so this turned out to be a weird android studio bug. I was initially running the code on my real nexus 4 device, and the onChange never gets called. However, after running it on an emulated device, it started working immediately. And now, it's working on my real device too.
I don't know the actual reason behind it, but if anyone in the future run into a problem where onChange won't get called, try switching device/emulators.
Cheers.
I debug the code on a device and have the same problem.
M'n solution was simply activate the device screen.
The screensaver was the problem..
i want privacy policy , disclaimer statement and a color picker as 1 time run activity when the app is installed . So how can i use persistent storage so that when we install and run the app for the first time privacy policy runs then clicking on button(next) goes to disclaimer activity then to color picker and finally to main activity. And when second time app is run it directly goes to main activity.
MAIN ACTIVITY:
public static final String PREFS_NAME = "MyPrefsFile"; // Name of prefs file; don't change this after it's saved something
//public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); // Get preferences file (0 = no option flags set)
boolean firstRun = settings.getBoolean("firstRun", false); // Is it first run? If not specified, use "true"
if (firstRun == false) {
Log.w("activity", "first time");
setContentView(R.layout.activity_gasfurnancediagnostics);
SharedPreferences.Editor editor = settings.edit(); // Open the editor for our settings
editor.putBoolean("firstRun", false); // It is no longer the first run
editor.apply(); // Save all changed settings
return;
} else {
Log.w("activity", "second time");
checkColor();
setContentView(R.layout.activity_theme);
return;
}
// setContentView(R.layout.activity_main);
//*** CHECKING COLOR IF IT WAS SET PREVIOUSLY ***/
}
public void checkColor()
{
// INITIALIZING THE SHARED PREFRENECES
SharedPreferences pref = getApplicationContext().getSharedPreferences("Colors", 0);
// CHECK IF WE HAVE COLOR_SET VALIRABLE IF NOT DEFAULT WILL BE 0
int color_set = pref.getInt("color_set", 0);
if(color_set==0){
Intent e = new Intent(getApplicationContext(), ThemeActivity.class);
startActivity(e);
return;
}
if(color_set==1)
{ // IF IT IS ALREADY SET IN THE PREVIOUS THAN THIS CAN BE USED FOR REDIRECTING TO OTHER CONTROLLER AND THE BELOW FUNCTIONS CAN BE USED IN THAT CONTROLLER FOR COLOR MODIFICATIUON
String color = pref.getString("color", null); // COLOR CODE
ActionBar mActionBar = getActionBar(); // GETTING ACTIONBAR
//final Button testbutn = (Button) findViewById(R.id.testbtn); // GETTING BUTTON
if (color.equals("red")) {
mActionBar.setBackgroundDrawable(new ColorDrawable(0xFFBA1E1E)); // CHANGES ACTION BAR COLOR
// testbutn.setBackgroundColor(0xFFFF6666);
// CHANGES BUTTON COLOR
} else if (color.equals("blue")) {
mActionBar.setBackgroundDrawable(new ColorDrawable(0xFF21a4dd)); // CHANGES ACTION BAR COLOR
// testbutn.setBackgroundColor(0xFFFF4B7E); // CHANGES BUTTON COLOR
}
else if (color.equals("yellow")) {
mActionBar.setBackgroundDrawable(new ColorDrawable(0xFFF6D72B)); // CHANGES ACTION BAR COLOR
// testbutn.setBackgroundColor(0xFFFF4B7E); // CHANGES BUTTON COLOR
}
mActionBar.setDisplayShowTitleEnabled(false); // THESE TWO STEPS ARE REQUIRED AFTER CHANGING THE ACTION BAR COLOR
mActionBar.setDisplayShowTitleEnabled(true); // THESE TWO STEPS ARE REQUIRED AFTER CHANGING THE ACTION BAR COLOR
}
GAS FURNANCE ACTIVITY
Button btnnext = (Button)findViewById(R.id.nextbtn);
btnnext.setOnClickListener((OnClickListener) this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(parent.getContext(), "Button Clicked"+ dataModel.getName(),Toast.LENGTH_LONG).show();
//Intent yes= new Intent(parent.getContext(), yes(dataModel.getName().class));
switch(v.getId())
{
case R.id.nextbtn:
Intent a = new Intent(getApplicationContext(), MainActivity.class);
startActivity(a);
break;
default:
}
}
package com.example.gasfurnancediagnostics;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class ThemeActivity extends Activity implements ColorPicker.OnColorChangedListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_theme);
Button blueBtn = (Button) findViewById(R.id.bluebtn);
blueBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//***** PERSISTANCE STORAGE INITIALIZATION****/
SharedPreferences pref = getApplicationContext().getSharedPreferences("Colors", 0);
// **** PERSISTANCE STORAGE EDITOR *** /
SharedPreferences.Editor editor = pref.edit();
editor.putString("color", "blue");
//**** DEFINING THE VALUE THAT THE COLOR IS ALREADY SET SO THAT WE CAN OMIT THIS ACTIVITY ***/
editor.putInt("color_set", 1);
//*** COMMITING ALL THE DETAILS TO THE STORAGE...
//** NOTE WITHOUT THIS THE DATA WONT BE SAVED
editor.commit();
Intent e = new Intent(getApplicationContext(), MainActivity.class);
startActivity(e);
}
});
Button redBtn = (Button) findViewById(R.id.redbtn);
redBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//***** PERSISTANCE STORAGE INITIALIZATION****/
SharedPreferences pref = getApplicationContext().getSharedPreferences("Colors", 0);
// **** PERSISTANCE STORAGE EDITOR *** /
SharedPreferences.Editor editor = pref.edit();
editor.putString("color", "red");
//**** DEFINING THE VALUE THAT THE COLOR IS ALREADY SET SO THAT WE CAN OMIT THIS ACTIVITY ***/
editor.putInt("color_set", 1);
//*** COMMITING ALL THE DETAILS TO THE STORAGE...
//** NOTE WITHOUT THIS THE DATA WONT BE SAVED
editor.commit();
Intent e = new Intent(getApplicationContext(), MainActivity.class);
startActivity(e);
}
});
Button yellowBtn = (Button) findViewById(R.id.yellowbtn);
yellowBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//***** PERSISTANCE STORAGE INITIALIZATION****/
SharedPreferences pref = getApplicationContext().getSharedPreferences("Colors", 0);
// **** PERSISTANCE STORAGE EDITOR *** /
SharedPreferences.Editor editor = pref.edit();
editor.putString("color", "yellow");
//**** DEFINING THE VALUE THAT THE COLOR IS ALREADY SET SO THAT WE CAN OMIT THIS ACTIVITY ***/
editor.putInt("color_set", 1);
//*** COMMITING ALL THE DETAILS TO THE STORAGE...
//** NOTE WITHOUT THIS THE DATA WONT BE SAVED
editor.commit();
Intent e = new Intent(getApplicationContext(), MainActivity.class);
startActivity(e);
}
});
}
#Override
public void colorChanged(String key, int color) {
// TODO Auto-generated method stub
}
}
SharedPreferences is what you are looking for,add this piece of code in your very first activity
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Boolean firstRun = preferences.getString("FirstRun",true);
if(true)
{
/*Open your activity here which you want to open for only once*/
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("FirstRun",false);
editor.apply();
}
else
{
/*Open your activity which you want to open later,generally*/
}
See this for detailed explaination and this
How to handle situations where a custom SherlockDialogFragment onCreateView() needs the activity to build its view?
More specifically, needs the activity onCreate() method to be executed before building its view. The custom SherlockDialogFragment is EffectSettingsDialog.
I can always reproduce the exception (that i mentioned in the comment section) in the emulator (tested with api level 10).
When the dialog is shown if I press ctrl-f11 (or ctrl-f12) the app crashes.
The app is thought to work in landscape mode (so I set android:screenOrientation="landscape" in the app manifest).
EffectSettingsDialog.java
/**
*
* #author
*
*/
public class EffectSettingsDialog extends SherlockDialogFragment
{
final static String DIALOG_TAG = "effect_settings_dialog";
final int UNKNOWN_BUTTON = 0;
final int OK_BUTTON = 1;
final int CANCEL_BUTTON = 2;
final int RESET_BUTTON = 3;
int pressed_button = UNKNOWN_BUTTON;
/**
*
*/
public EffectSettingsDialog( )
{
super();
CLog.i( "EffectSettingsDialog", "EffectSettingsDialog()" );
}
/**
* Create a new instance of WelcomeDialog.
*/
static EffectSettingsDialog newInstance()
{
EffectSettingsDialog d = new EffectSettingsDialog();
return d;
}
/**
*
*/
static boolean showNewInstance( FragmentActivity activity, int fx_id )
{
if ( fx_id == -1 )
return false;
Fragment prev = activity.getSupportFragmentManager().findFragmentByTag( EffectSettingsDialog.DIALOG_TAG );
if (prev != null)
return false;
EffectSettingsDialog d = EffectSettingsDialog.newInstance();
// Supply fx_id parameter to the fragment
Bundle args = new Bundle();
args.putInt( "fx_id", fx_id );
d.setArguments(args);
d.show( activity.getSupportFragmentManager(), EffectSettingsDialog.DIALOG_TAG );
return true;
}
#Override
public void onCreate( Bundle savedInstanceState )
{
CLog.i( "EffectSettingsDialog", "onCreate()" );
super.onCreate(savedInstanceState);
int style = SherlockDialogFragment.STYLE_NO_TITLE;
int theme = getTheme();
setStyle(style, theme );//, theme);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceStateBundle )
{
CLog.i( "EffectSettingsDialog", "onCreateDialog()" );
// TODO Auto-generated method stub
Dialog d = super.onCreateDialog( savedInstanceStateBundle );
return d;
}
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState )
{
CLog.i( "EffectSettingsDialog", "onCreateView()" );
/// Here i need to call ((MyActivity)getActivity()).getData() to properly initialize the view. Initialization code omitted...
getDialog().getWindow().setBackgroundDrawableResource( R.color.transparent );//translucent_black );
getDialog().getWindow().clearFlags( WindowManager.LayoutParams.FLAG_DIM_BEHIND );
return v;
}
}
In the activity (in the onClick() method), i use the following code:
EffectSettingsDialog.showNewInstance( this, fx_id );
This happens when the user touches a specific button.
JDT and other plugins for Eclipse decorate the editor title image with problem status (compilation errors etc.). In my plugin I want to mimic that behaviour.
However, looking at the sources, JDT seems to do a lot of extra handling to do the decoration.
Decorators, especially lightweight ditto, is a handy way of doing decorations on icons, but I can find no way to programatically enable them for the title image of an editor. (And I don't want to pull in all of JDT UI in my plugin...)
Is there such a way or do I need to implement my own ILabelProvider and then
public void updatedTitleImage(Image image) {
setTitleImage(image);
}
like the JavaEditor does?
There seems to be no way to use decorators with the editor title image (as of 3.7 at least).
I ended up creating a EditorLabelUpdator which implemented the IResourceChangeListener interface (to find out when markers changed), basically the resourceChanged() method. It then uses a simple decorator-type class built from the pattern of OverlayImageIcon (of which you can find a lot of examples on Google).
The constructor is called from the initalization of the editor, sending the editor as a parameter which is saved for getting at the resource and its title icon.
The editor also had to be amended with a callback method triggering the title icon updating (updatedTitleImage(Image image)).
This is the core of the code I got:
public void resourceChanged(IResourceChangeEvent event) {
if (isMarkerChangeForResource(event, editor)) {
/* Changes in markers on this resource, so re-decorate title image */
decorate();
}
}
private boolean isMarkerChangeForResource(IResourceChangeEvent event, AlanEditor editor) {
boolean isMarkerChangeForThisResource;
final IResource resource = ResourceUtil.getResource(editor.getEditorInput());
final IPath path = resource.getFullPath();
IResourceDelta delta = event.getDelta().findMember(path);
isMarkerChangeForThisResource = (delta != null) && ((delta.getFlags() & IResourceDelta.MARKERS) != 0);
return isMarkerChangeForThisResource;
}
public void decorate() {
Shell shell = editor.getEditorSite().getShell();
if (shell != null && !shell.isDisposed()) {
shell.getDisplay().syncExec(new Runnable() {
public void run() {
Image decoratedImage = decorateImage(editor.getTitleImage(), getSeverity());
editor.updatedTitleImage(decoratedImage);
}
});
}
}
private Image decorateImage(Image titleImage, int severity) {
final ImageRegistry registry = AlanIDEPlugin.getDefault().getImageRegistry();
String key = createKey(severity);
ImageDescriptor descriptor = AlanIDEPlugin.getImageDescriptor(key);
if (descriptor != null)
return descriptor.createImage();
OverlayImageDescriptor overlayImageDescriptor = buildDecoratedImage(severity, key);
registry.put(key, overlayImageDescriptor);
return overlayImageDescriptor.createImage();
}
private String createKey(int severity) {
String key;
switch (severity) {
case IMarker.SEVERITY_ERROR: key = EDITOR_TITLE_ICON + ".error"; break;
case IMarker.SEVERITY_WARNING: key = EDITOR_TITLE_ICON + ".warning"; break;
default: key = EDITOR_TITLE_ICON; break;
}
return key;
}
private OverlayImageDescriptor buildDecoratedImage(int severity, String key) {
ImageDescriptor overlay = null;
if (severity >= IMarker.SEVERITY_ERROR)
overlay = AlanIDEPlugin.getImageDescriptor("ovr16.error_ovr");
else if (severity == IMarker.SEVERITY_WARNING)
overlay = AlanIDEPlugin.getImageDescriptor("ovr16.warning_ovr");
ImageDescriptor baseImage = AlanIDEPlugin.getImageDescriptor(EDITOR_TITLE_ICON);
OverlayImageDescriptor overlayIcon = new OverlayImageDescriptor(baseImage);
if (overlay != null)
overlayIcon.addOverlay(overlay, IDecoration.BOTTOM_LEFT);
return overlayIcon;
}
private int getSeverity() {
int severity = 0;
try {
final IResource resource = ResourceUtil.getResource(editor.getEditorInput());
severity = resource.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE);
} catch (CoreException e) {
// Might be a project that is not open
}
return severity;
}
This was the simplest solution I could come up with.
Yes, there is an extension point which you can use to achieve that. See the code below:
<!--define the decorator -->
<extension point="org.eclipse.ui.decorators">
<decorator
adaptable="true"
class="org.example.PackageExplorerDecorator"
id="org.example.PackageExplorerDecorator"
label="File Decorator"
lightweight="true"
state="true">
<enablement>
<or>
<objectClass
name="org.eclipse.jdt.core.IMethod">
</objectClass>
<objectClass
name="org.eclipse.core.resources.IResource">
</objectClass>
</or>
</enablement>
For the PackageExplorerDecorator: extends LabelProvider implements ILightweightLabelDecorator
Does anyone know how to display an Icon and a Text for the displaying field in ext-gwts combobo? I tried everything.
In the third ComboBox of this example (klick me) there is an icon and the text for the selectable values. This was no problem with the example template. But i want to show the icon and the text for the selected value too. How can i manage this?
I have a Model class for the icon and the text.
public class Language extends DbBaseObjectModel {
private static final long serialVersionUID = 8477520184310335811L;
public Language(String langIcon, String langName) {
setLangIcon(langIcon);
setLangName(langName);
}
public String getLangIcon() {
return get("langIcon");
}
public String getLangName() {
return get("langName");
}
public void setLangIcon(String langIcon) {
set("langIcon", langIcon);
}
public void setLangName(String langName) {
set("langName", langName);
}
}
This is how i initalize the ComboBox. I want to change the displayField "langName".
final ListStore<Language> countries = new ListStore<Language>();
final Language german = new Language("de_DE", "Deutsch");
final Language english = new Language("en_GB", "Englisch");
countries.add(german);
countries.add(english);
final ComboBox<Language> combo = new ComboBox<Language>();
combo.setWidth(100);
combo.setStore(countries);
combo.setDisplayField("langName");
combo.setTemplate(getFlagTemplate());
combo.setTypeAhead(true);
combo.setTriggerAction(TriggerAction.ALL);
combo.setValue(german);
This is the template for the ComboBox two show the selectable values.
private native String getFlagTemplate() /*-{
return [ '<tpl for=".">', '<div class="x-combo-list-item">',
'<img src="resources/images/lang/{langIcon}.png">',
' {langName}</div>', '</tpl>' ].join("");
}-*/;
How can i use an template for the displayField or is there an other possibility?
Thanks!
You need to implement a com.extjs.gxt.ui.client.widget.form.ListModelPropertyEditor.
The com.extjs.gxt.ui.client.widget.form.PropertyEditor#getStringValue returns the string that should be displayed and the com.extjs.gxt.ui.client.widget.form.PropertyEditor#convertStringValue converts the displayed string back into the model.
This isn't a very performant implementation but it works:
public class TemplateModelPropertyEditor<D extends ModelData> extends
ListModelPropertyEditor<D> {
/** Template to render the model. */
private XTemplate template;
#Override
public D convertStringValue(final String value) {
for (final D d : models) {
final String val = getStringValue(d);
if (value.equals(val)) {
return d;
}
}
return null;
}
#Override
public String getStringValue(final D value) {
if (template != null) {
final Element div = DOM.createDiv();
template.overwrite(div, Util.getJsObject(value));
return div.getInnerText();
}
final Object obj = value.get(displayProperty);
if (obj != null) {
return obj.toString();
}
return null;
}
public void setSimpleTemplate(final String html) {
template = XTemplate.create(html);
}
}
Usage:
TemplateModelPropertyEditor<Language> propertyEditor = new TemplateModelPropertyEditor<Language>();
propertyEditor.setSimpleTemplate(getFlagTemplate());
combo.setPropertyEditor(propertyEditor);
which imports?
I added these ones:
import com.extjs.gxt.ui.client.core.XTemplate;
import com.extjs.gxt.ui.client.util.Util;
import com.extjs.gxt.ui.client.widget.form.ListModelPropertyEditor;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
Everthing works fine, but it don't display an icon. When i debug the return div.getInnerText() method throws an error called: Method "getInnerText" with signature "()Ljava/lang/String;" is not applicable on this object.
The created div element looks okay
<DIV><DIV class=x-combo-list-item><IMG src="http://127.0.0.1:8888/resources/images/lang/de_DE.png"> Deutsch</DIV></DIV>