Fragments

This commit is contained in:
serso
2012-09-27 11:34:06 +04:00
parent 9987670225
commit 388c40d912
10 changed files with 1338 additions and 1319 deletions

View File

@@ -1,376 +1,377 @@
/*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com
*/
package org.solovyev.android.calculator;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import net.robotmedia.billing.BillingController;
import net.robotmedia.billing.IBillingObserver;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.AndroidUtils;
import org.solovyev.android.FontSizeAdjuster;
import org.solovyev.android.calculator.about.CalculatorReleaseNotesActivity;
import org.solovyev.android.calculator.history.CalculatorHistoryFragment;
import org.solovyev.android.calculator.history.CalculatorSavedHistoryFragment;
import org.solovyev.android.calculator.math.edit.CalculatorVarsFragment;
import org.solovyev.android.calculator.model.VarCategory;
import org.solovyev.android.fragments.FragmentUtils;
import org.solovyev.android.prefs.Preference;
import org.solovyev.android.view.ColorButton;
import org.solovyev.common.equals.EqualsTool;
import org.solovyev.common.history.HistoryAction;
import org.solovyev.common.text.StringUtils;
public class CalculatorActivity extends SherlockFragmentActivity implements FontSizeAdjuster, SharedPreferences.OnSharedPreferenceChangeListener {
@NotNull
public static final String TAG = CalculatorActivity.class.getSimpleName();
private static final int HVGA_WIDTH_PIXELS = 320;
@Nullable
private IBillingObserver billingObserver;
private boolean useBackAsPrev;
@NotNull
private CalculatorActivityHelper activityHelper;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
CalculatorApplication.registerOnRemoteStackTrace();
/*final boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);*/
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final CalculatorPreferences.Gui.Layout layout = CalculatorPreferences.Gui.layout.getPreferenceNoError(preferences);
activityHelper = CalculatorApplication.getInstance().createActivityHelper(layout.getLayoutId(), TAG);
activityHelper.logDebug("onCreate");
activityHelper.onCreate(this, savedInstanceState);
super.onCreate(savedInstanceState);
activityHelper.logDebug("super.onCreate");
if (findViewById(R.id.main_second_pane) != null) {
activityHelper.addTab(this, "history", CalculatorHistoryFragment.class, null, R.string.c_history, R.id.main_second_pane);
activityHelper.addTab(this, "saved_history", CalculatorSavedHistoryFragment.class, null, R.string.c_saved_history, R.id.main_second_pane);
for (VarCategory category : VarCategory.getCategoriesByTabOrder()) {
activityHelper.addTab(this, "vars_" + category.name(), CalculatorVarsFragment.class, CalculatorVarsFragment.createBundleFor(category.name()), category.getCaptionId(), R.id.main_second_pane);
}
activityHelper.restoreSavedTab(this);
}
CalculatorKeyboardFragment.fixThemeParameters(true, activityHelper.getTheme(), this.getWindow().getDecorView());
FragmentUtils.createFragment(this, CalculatorEditorFragment.class, R.id.editorContainer, "editor");
FragmentUtils.createFragment(this, CalculatorDisplayFragment.class, R.id.displayContainer, "display");
FragmentUtils.createFragment(this, CalculatorKeyboardFragment.class, R.id.keyboardContainer, "keyboard");
/*if (customTitleSupported) {
try {
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.calc_title);
final CalculatorAdditionalTitle additionalAdditionalTitleText = (CalculatorAdditionalTitle)findViewById(R.id.additional_title_text);
additionalAdditionalTitleText.init(preferences);
preferences.registerOnSharedPreferenceChangeListener(additionalAdditionalTitleText);
} catch (ClassCastException e) {
// super fix for issue with class cast in android.view.Window.setFeatureInt() (see app error reports)
Log.e(CalculatorActivity.class.getName(), e.getMessage(), e);
}
}*/
billingObserver = new CalculatorBillingObserver(this);
BillingController.registerObserver(billingObserver);
this.useBackAsPrev = CalculatorPreferences.Gui.usePrevAsBack.getPreference(preferences);
firstTimeInit(preferences, this);
// init billing controller
BillingController.checkBillingSupported(this);
toggleOrientationChange(preferences);
CalculatorKeyboardFragment.toggleEqualsButton(preferences, this, activityHelper.getTheme(), findViewById(R.id.main_layout));
preferences.registerOnSharedPreferenceChangeListener(this);
}
@NotNull
private AndroidCalculator getCalculator() {
return ((AndroidCalculator) CalculatorLocatorImpl.getInstance().getCalculator());
}
private static void firstTimeInit(@NotNull SharedPreferences preferences, @NotNull Context context) {
final Integer appOpenedCounter = CalculatorPreferences.appOpenedCounter.getPreference(preferences);
if (appOpenedCounter != null) {
CalculatorPreferences.appOpenedCounter.putPreference(preferences, appOpenedCounter + 1);
}
final Integer savedVersion = CalculatorPreferences.appVersion.getPreference(preferences);
final int appVersion = AndroidUtils.getAppVersionCode(context, CalculatorActivity.class.getPackage().getName());
CalculatorPreferences.appVersion.putPreference(preferences, appVersion);
boolean dialogShown = false;
if (EqualsTool.areEqual(savedVersion, CalculatorPreferences.appVersion.getDefaultValue())) {
// new start
final AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(R.string.c_first_start_text);
builder.setPositiveButton(android.R.string.ok, null);
builder.setTitle(R.string.c_first_start_text_title);
builder.create().show();
dialogShown = true;
} else {
if (savedVersion < appVersion) {
final boolean showReleaseNotes = CalculatorPreferences.Gui.showReleaseNotes.getPreference(preferences);
if (showReleaseNotes) {
final String releaseNotes = CalculatorReleaseNotesActivity.getReleaseNotes(context, savedVersion + 1);
if (!StringUtils.isEmpty(releaseNotes)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(Html.fromHtml(releaseNotes));
builder.setPositiveButton(android.R.string.ok, null);
builder.setTitle(R.string.c_release_notes);
builder.create().show();
dialogShown = true;
}
}
}
}
//Log.d(this.getClass().getName(), "Application was opened " + appOpenedCounter + " time!");
if (!dialogShown) {
if (appOpenedCounter != null && appOpenedCounter > 10) {
dialogShown = showSpecialWindow(preferences, CalculatorPreferences.Gui.feedbackWindowShown, R.layout.feedback, R.id.feedbackText, context);
}
}
if (!dialogShown) {
dialogShown = showSpecialWindow(preferences, CalculatorPreferences.Gui.notesppAnnounceShown, R.layout.notespp_announce, R.id.notespp_announce, context);
}
}
private static boolean showSpecialWindow(@NotNull SharedPreferences preferences, @NotNull Preference<Boolean> specialWindowShownPref, int layoutId, int textViewId, @NotNull Context context) {
boolean result = false;
final Boolean specialWindowShown = specialWindowShownPref.getPreference(preferences);
if ( specialWindowShown != null && !specialWindowShown ) {
final LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
final View view = layoutInflater.inflate(layoutId, null);
final TextView feedbackTextView = (TextView) view.findViewById(textViewId);
feedbackTextView.setMovementMethod(LinkMovementMethod.getInstance());
final AlertDialog.Builder builder = new AlertDialog.Builder(context).setView(view);
builder.setPositiveButton(android.R.string.ok, null);
builder.create().show();
result = true;
specialWindowShownPref.putPreference(preferences, true);
}
return result;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (useBackAsPrev) {
getCalculator().doHistoryAction(HistoryAction.undo);
return true;
}
}
return super.onKeyDown(keyCode, event);
}
@SuppressWarnings({"UnusedDeclaration"})
public void equalsButtonClickHandler(@NotNull View v) {
getCalculator().evaluate();
}
/**
* The font sizes in the layout files are specified for a HVGA display.
* Adjust the font sizes accordingly if we are running on a different
* display.
*/
@Override
public void adjustFontSize(@NotNull TextView view) {
/*float fontPixelSize = view.getTextSize();
Display display = getWindowManager().getDefaultDisplay();
int h = Math.min(display.getWidth(), display.getHeight());
float ratio = (float) h / HVGA_WIDTH_PIXELS;
view.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontPixelSize * ratio);*/
}
@Override
protected void onPause() {
super.onPause();
activityHelper.onPause(this);
}
@Override
protected void onResume() {
super.onResume();
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final CalculatorPreferences.Gui.Layout newLayout = CalculatorPreferences.Gui.layout.getPreference(preferences);
if ( newLayout.getLayoutId() != activityHelper.getLayoutId() ) {
AndroidUtils.restartActivity(this);
}
this.activityHelper.onResume(this);
}
@Override
protected void onDestroy() {
if (billingObserver != null) {
BillingController.unregisterObserver(billingObserver);
}
activityHelper.onDestroy(this);
super.onDestroy();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences preferences, @Nullable String key) {
if ( CalculatorPreferences.Gui.usePrevAsBack.getKey().equals(key) ) {
useBackAsPrev = CalculatorPreferences.Gui.usePrevAsBack.getPreference(preferences);
}
if ( CalculatorPreferences.Gui.autoOrientation.getKey().equals(key) ) {
toggleOrientationChange(preferences);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
activityHelper.onSaveInstanceState(this, outState);
}
private void toggleOrientationChange(@Nullable SharedPreferences preferences) {
preferences = preferences == null ? PreferenceManager.getDefaultSharedPreferences(this) : preferences;
if (CalculatorPreferences.Gui.autoOrientation.getPreference(preferences)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
/*
**********************************************************************
*
* BUTTON HANDLERS
*
**********************************************************************
*/
@SuppressWarnings({"UnusedDeclaration"})
public void elementaryButtonClickHandler(@NotNull View v) {
throw new UnsupportedOperationException("Not implemented yet!");
}
@SuppressWarnings({"UnusedDeclaration"})
public void historyButtonClickHandler(@NotNull View v) {
CalculatorActivityLauncher.showHistory(this);
}
@SuppressWarnings({"UnusedDeclaration"})
public void eraseButtonClickHandler(@NotNull View v) {
CalculatorLocatorImpl.getInstance().getEditor().erase();
}
@SuppressWarnings({"UnusedDeclaration"})
public void simplifyButtonClickHandler(@NotNull View v) {
throw new UnsupportedOperationException("Not implemented yet!");
}
@SuppressWarnings({"UnusedDeclaration"})
public void moveLeftButtonClickHandler(@NotNull View v) {
getKeyboard().moveCursorLeft();
}
@SuppressWarnings({"UnusedDeclaration"})
public void moveRightButtonClickHandler(@NotNull View v) {
getKeyboard().moveCursorRight();
}
@SuppressWarnings({"UnusedDeclaration"})
public void pasteButtonClickHandler(@NotNull View v) {
getKeyboard().pasteButtonPressed();
}
@SuppressWarnings({"UnusedDeclaration"})
public void copyButtonClickHandler(@NotNull View v) {
getKeyboard().copyButtonPressed();
}
@NotNull
private static CalculatorKeyboard getKeyboard() {
return CalculatorLocatorImpl.getInstance().getKeyboard();
}
@SuppressWarnings({"UnusedDeclaration"})
public void clearButtonClickHandler(@NotNull View v) {
getKeyboard().clearButtonPressed();
}
@SuppressWarnings({"UnusedDeclaration"})
public void digitButtonClickHandler(@NotNull View v) {
Log.d(String.valueOf(v.getId()), "digitButtonClickHandler() for: " + v.getId() + ". Pressed: " + v.isPressed());
if (((ColorButton) v).isShowText()) {
getKeyboard().digitButtonPressed(((ColorButton) v).getText().toString());
}
}
@SuppressWarnings({"UnusedDeclaration"})
public void functionsButtonClickHandler(@NotNull View v) {
CalculatorActivityLauncher.showFunctions(this);
}
@SuppressWarnings({"UnusedDeclaration"})
public void operatorsButtonClickHandler(@NotNull View v) {
CalculatorActivityLauncher.showOperators(this);
}
public static void operatorsButtonClickHandler(@NotNull Activity activity) {
CalculatorActivityLauncher.showOperators(activity);
}
@SuppressWarnings({"UnusedDeclaration"})
public void varsButtonClickHandler(@NotNull View v) {
CalculatorActivityLauncher.showVars(this);
}
@SuppressWarnings({"UnusedDeclaration"})
public void donateButtonClickHandler(@NotNull View v) {
CalculatorApplication.showDonationDialog(this);
}
/*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com
*/
package org.solovyev.android.calculator;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import net.robotmedia.billing.BillingController;
import net.robotmedia.billing.IBillingObserver;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.AndroidUtils;
import org.solovyev.android.FontSizeAdjuster;
import org.solovyev.android.calculator.about.CalculatorReleaseNotesActivity;
import org.solovyev.android.calculator.history.CalculatorHistoryFragment;
import org.solovyev.android.calculator.history.CalculatorSavedHistoryFragment;
import org.solovyev.android.calculator.math.edit.CalculatorFunctionsFragment;
import org.solovyev.android.calculator.math.edit.CalculatorOperatorsFragment;
import org.solovyev.android.calculator.math.edit.CalculatorVarsFragment;
import org.solovyev.android.fragments.FragmentUtils;
import org.solovyev.android.prefs.Preference;
import org.solovyev.android.view.ColorButton;
import org.solovyev.common.equals.EqualsTool;
import org.solovyev.common.history.HistoryAction;
import org.solovyev.common.text.StringUtils;
public class CalculatorActivity extends SherlockFragmentActivity implements FontSizeAdjuster, SharedPreferences.OnSharedPreferenceChangeListener {
@NotNull
public static final String TAG = CalculatorActivity.class.getSimpleName();
private static final int HVGA_WIDTH_PIXELS = 320;
@Nullable
private IBillingObserver billingObserver;
private boolean useBackAsPrev;
@NotNull
private CalculatorActivityHelper activityHelper;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
CalculatorApplication.registerOnRemoteStackTrace();
/*final boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);*/
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final CalculatorPreferences.Gui.Layout layout = CalculatorPreferences.Gui.layout.getPreferenceNoError(preferences);
activityHelper = CalculatorApplication.getInstance().createActivityHelper(layout.getLayoutId(), TAG);
activityHelper.logDebug("onCreate");
activityHelper.onCreate(this, savedInstanceState);
super.onCreate(savedInstanceState);
activityHelper.logDebug("super.onCreate");
if (findViewById(R.id.main_second_pane) != null) {
activityHelper.addTab(this, "history", CalculatorHistoryFragment.class, null, R.string.c_history, R.id.main_second_pane);
activityHelper.addTab(this, "saved_history", CalculatorSavedHistoryFragment.class, null, R.string.c_saved_history, R.id.main_second_pane);
activityHelper.addTab(this, "vars", CalculatorVarsFragment.class, null, R.string.c_vars, R.id.main_second_pane);
activityHelper.addTab(this, "functions", CalculatorFunctionsFragment.class, null, R.string.c_functions, R.id.main_second_pane);
activityHelper.addTab(this, "operators", CalculatorOperatorsFragment.class, null, R.string.c_operators, R.id.main_second_pane);
activityHelper.restoreSavedTab(this);
}
CalculatorKeyboardFragment.fixThemeParameters(true, activityHelper.getTheme(), this.getWindow().getDecorView());
FragmentUtils.createFragment(this, CalculatorEditorFragment.class, R.id.editorContainer, "editor");
FragmentUtils.createFragment(this, CalculatorDisplayFragment.class, R.id.displayContainer, "display");
FragmentUtils.createFragment(this, CalculatorKeyboardFragment.class, R.id.keyboardContainer, "keyboard");
/*if (customTitleSupported) {
try {
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.calc_title);
final CalculatorAdditionalTitle additionalAdditionalTitleText = (CalculatorAdditionalTitle)findViewById(R.id.additional_title_text);
additionalAdditionalTitleText.init(preferences);
preferences.registerOnSharedPreferenceChangeListener(additionalAdditionalTitleText);
} catch (ClassCastException e) {
// super fix for issue with class cast in android.view.Window.setFeatureInt() (see app error reports)
Log.e(CalculatorActivity.class.getName(), e.getMessage(), e);
}
}*/
billingObserver = new CalculatorBillingObserver(this);
BillingController.registerObserver(billingObserver);
this.useBackAsPrev = CalculatorPreferences.Gui.usePrevAsBack.getPreference(preferences);
firstTimeInit(preferences, this);
// init billing controller
BillingController.checkBillingSupported(this);
toggleOrientationChange(preferences);
CalculatorKeyboardFragment.toggleEqualsButton(preferences, this, activityHelper.getTheme(), findViewById(R.id.main_layout));
preferences.registerOnSharedPreferenceChangeListener(this);
}
@NotNull
private AndroidCalculator getCalculator() {
return ((AndroidCalculator) CalculatorLocatorImpl.getInstance().getCalculator());
}
private static void firstTimeInit(@NotNull SharedPreferences preferences, @NotNull Context context) {
final Integer appOpenedCounter = CalculatorPreferences.appOpenedCounter.getPreference(preferences);
if (appOpenedCounter != null) {
CalculatorPreferences.appOpenedCounter.putPreference(preferences, appOpenedCounter + 1);
}
final Integer savedVersion = CalculatorPreferences.appVersion.getPreference(preferences);
final int appVersion = AndroidUtils.getAppVersionCode(context, CalculatorActivity.class.getPackage().getName());
CalculatorPreferences.appVersion.putPreference(preferences, appVersion);
boolean dialogShown = false;
if (EqualsTool.areEqual(savedVersion, CalculatorPreferences.appVersion.getDefaultValue())) {
// new start
final AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(R.string.c_first_start_text);
builder.setPositiveButton(android.R.string.ok, null);
builder.setTitle(R.string.c_first_start_text_title);
builder.create().show();
dialogShown = true;
} else {
if (savedVersion < appVersion) {
final boolean showReleaseNotes = CalculatorPreferences.Gui.showReleaseNotes.getPreference(preferences);
if (showReleaseNotes) {
final String releaseNotes = CalculatorReleaseNotesActivity.getReleaseNotes(context, savedVersion + 1);
if (!StringUtils.isEmpty(releaseNotes)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(Html.fromHtml(releaseNotes));
builder.setPositiveButton(android.R.string.ok, null);
builder.setTitle(R.string.c_release_notes);
builder.create().show();
dialogShown = true;
}
}
}
}
//Log.d(this.getClass().getName(), "Application was opened " + appOpenedCounter + " time!");
if (!dialogShown) {
if (appOpenedCounter != null && appOpenedCounter > 10) {
dialogShown = showSpecialWindow(preferences, CalculatorPreferences.Gui.feedbackWindowShown, R.layout.feedback, R.id.feedbackText, context);
}
}
if (!dialogShown) {
dialogShown = showSpecialWindow(preferences, CalculatorPreferences.Gui.notesppAnnounceShown, R.layout.notespp_announce, R.id.notespp_announce, context);
}
}
private static boolean showSpecialWindow(@NotNull SharedPreferences preferences, @NotNull Preference<Boolean> specialWindowShownPref, int layoutId, int textViewId, @NotNull Context context) {
boolean result = false;
final Boolean specialWindowShown = specialWindowShownPref.getPreference(preferences);
if ( specialWindowShown != null && !specialWindowShown ) {
final LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
final View view = layoutInflater.inflate(layoutId, null);
final TextView feedbackTextView = (TextView) view.findViewById(textViewId);
feedbackTextView.setMovementMethod(LinkMovementMethod.getInstance());
final AlertDialog.Builder builder = new AlertDialog.Builder(context).setView(view);
builder.setPositiveButton(android.R.string.ok, null);
builder.create().show();
result = true;
specialWindowShownPref.putPreference(preferences, true);
}
return result;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (useBackAsPrev) {
getCalculator().doHistoryAction(HistoryAction.undo);
return true;
}
}
return super.onKeyDown(keyCode, event);
}
@SuppressWarnings({"UnusedDeclaration"})
public void equalsButtonClickHandler(@NotNull View v) {
getCalculator().evaluate();
}
/**
* The font sizes in the layout files are specified for a HVGA display.
* Adjust the font sizes accordingly if we are running on a different
* display.
*/
@Override
public void adjustFontSize(@NotNull TextView view) {
/*float fontPixelSize = view.getTextSize();
Display display = getWindowManager().getDefaultDisplay();
int h = Math.min(display.getWidth(), display.getHeight());
float ratio = (float) h / HVGA_WIDTH_PIXELS;
view.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontPixelSize * ratio);*/
}
@Override
protected void onPause() {
super.onPause();
activityHelper.onPause(this);
}
@Override
protected void onResume() {
super.onResume();
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final CalculatorPreferences.Gui.Layout newLayout = CalculatorPreferences.Gui.layout.getPreference(preferences);
if ( newLayout.getLayoutId() != activityHelper.getLayoutId() ) {
AndroidUtils.restartActivity(this);
}
this.activityHelper.onResume(this);
}
@Override
protected void onDestroy() {
if (billingObserver != null) {
BillingController.unregisterObserver(billingObserver);
}
activityHelper.onDestroy(this);
super.onDestroy();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences preferences, @Nullable String key) {
if ( CalculatorPreferences.Gui.usePrevAsBack.getKey().equals(key) ) {
useBackAsPrev = CalculatorPreferences.Gui.usePrevAsBack.getPreference(preferences);
}
if ( CalculatorPreferences.Gui.autoOrientation.getKey().equals(key) ) {
toggleOrientationChange(preferences);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
activityHelper.onSaveInstanceState(this, outState);
}
private void toggleOrientationChange(@Nullable SharedPreferences preferences) {
preferences = preferences == null ? PreferenceManager.getDefaultSharedPreferences(this) : preferences;
if (CalculatorPreferences.Gui.autoOrientation.getPreference(preferences)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
/*
**********************************************************************
*
* BUTTON HANDLERS
*
**********************************************************************
*/
@SuppressWarnings({"UnusedDeclaration"})
public void elementaryButtonClickHandler(@NotNull View v) {
throw new UnsupportedOperationException("Not implemented yet!");
}
@SuppressWarnings({"UnusedDeclaration"})
public void historyButtonClickHandler(@NotNull View v) {
CalculatorActivityLauncher.showHistory(this);
}
@SuppressWarnings({"UnusedDeclaration"})
public void eraseButtonClickHandler(@NotNull View v) {
CalculatorLocatorImpl.getInstance().getEditor().erase();
}
@SuppressWarnings({"UnusedDeclaration"})
public void simplifyButtonClickHandler(@NotNull View v) {
throw new UnsupportedOperationException("Not implemented yet!");
}
@SuppressWarnings({"UnusedDeclaration"})
public void moveLeftButtonClickHandler(@NotNull View v) {
getKeyboard().moveCursorLeft();
}
@SuppressWarnings({"UnusedDeclaration"})
public void moveRightButtonClickHandler(@NotNull View v) {
getKeyboard().moveCursorRight();
}
@SuppressWarnings({"UnusedDeclaration"})
public void pasteButtonClickHandler(@NotNull View v) {
getKeyboard().pasteButtonPressed();
}
@SuppressWarnings({"UnusedDeclaration"})
public void copyButtonClickHandler(@NotNull View v) {
getKeyboard().copyButtonPressed();
}
@NotNull
private static CalculatorKeyboard getKeyboard() {
return CalculatorLocatorImpl.getInstance().getKeyboard();
}
@SuppressWarnings({"UnusedDeclaration"})
public void clearButtonClickHandler(@NotNull View v) {
getKeyboard().clearButtonPressed();
}
@SuppressWarnings({"UnusedDeclaration"})
public void digitButtonClickHandler(@NotNull View v) {
Log.d(String.valueOf(v.getId()), "digitButtonClickHandler() for: " + v.getId() + ". Pressed: " + v.isPressed());
if (((ColorButton) v).isShowText()) {
getKeyboard().digitButtonPressed(((ColorButton) v).getText().toString());
}
}
@SuppressWarnings({"UnusedDeclaration"})
public void functionsButtonClickHandler(@NotNull View v) {
CalculatorActivityLauncher.showFunctions(this);
}
@SuppressWarnings({"UnusedDeclaration"})
public void operatorsButtonClickHandler(@NotNull View v) {
CalculatorActivityLauncher.showOperators(this);
}
public static void operatorsButtonClickHandler(@NotNull Activity activity) {
CalculatorActivityLauncher.showOperators(activity);
}
@SuppressWarnings({"UnusedDeclaration"})
public void varsButtonClickHandler(@NotNull View v) {
CalculatorActivityLauncher.showVars(this);
}
@SuppressWarnings({"UnusedDeclaration"})
public void donateButtonClickHandler(@NotNull View v) {
CalculatorApplication.showDonationDialog(this);
}
}

View File

@@ -1,82 +1,82 @@
package org.solovyev.android.calculator;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import jscl.math.Generic;
import jscl.math.function.Constant;
import org.achartengine.ChartFactory;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.about.CalculatorAboutTabActivity;
import org.solovyev.android.calculator.help.CalculatorHelpTabActivity;
import org.solovyev.android.calculator.history.CalculatorHistoryFragmentActivity;
import org.solovyev.android.calculator.math.edit.CalculatorFunctionsFragmentActivity;
import org.solovyev.android.calculator.math.edit.CalculatorOperatorsActivity;
import org.solovyev.android.calculator.math.edit.CalculatorVarsFragment;
import org.solovyev.android.calculator.math.edit.CalculatorVarsFragmentActivity;
import org.solovyev.android.calculator.plot.CalculatorPlotActivity;
import org.solovyev.common.text.StringUtils;
/**
* User: serso
* Date: 11/2/11
* Time: 2:18 PM
*/
public class CalculatorActivityLauncher {
public static void showHistory(@NotNull final Context context) {
context.startActivity(new Intent(context, CalculatorHistoryFragmentActivity.class));
}
public static void showHelp(@NotNull final Context context) {
context.startActivity(new Intent(context, CalculatorHelpTabActivity.class));
}
public static void showSettings(@NotNull final Context context) {
context.startActivity(new Intent(context, CalculatorPreferencesActivity.class));
}
public static void showAbout(@NotNull final Context context) {
context.startActivity(new Intent(context, CalculatorAboutTabActivity.class));
}
public static void showFunctions(@NotNull final Context context) {
context.startActivity(new Intent(context, CalculatorFunctionsFragmentActivity.class));
}
public static void showOperators(@NotNull final Context context) {
context.startActivity(new Intent(context, CalculatorOperatorsActivity.class));
}
public static void showVars(@NotNull final Context context) {
context.startActivity(new Intent(context, CalculatorVarsFragmentActivity.class));
}
public static void plotGraph(@NotNull final Context context, @NotNull Generic generic, @NotNull Constant constant){
final Intent intent = new Intent();
intent.putExtra(ChartFactory.TITLE, context.getString(R.string.c_graph));
intent.putExtra(CalculatorPlotActivity.INPUT, new CalculatorPlotActivity.Input(generic.toString(), constant.getName()));
intent.setClass(context, CalculatorPlotActivity.class);
context.startActivity(intent);
}
public static void createVar(@NotNull final Context context, @NotNull CalculatorDisplay calculatorDisplay) {
final CalculatorDisplayViewState viewState = calculatorDisplay.getViewState();
if (viewState.isValid() ) {
final String varValue = viewState.getText();
if (!StringUtils.isEmpty(varValue)) {
if (CalculatorVarsFragment.isValidValue(varValue)) {
final Intent intent = new Intent(context, CalculatorVarsFragmentActivity.class);
intent.putExtra(CalculatorVarsFragment.CREATE_VAR_EXTRA_STRING, varValue);
context.startActivity(intent);
} else {
Toast.makeText(context, R.string.c_not_valid_result, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, R.string.c_empty_var_error, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, R.string.c_not_valid_result, Toast.LENGTH_SHORT).show();
}
}
}
package org.solovyev.android.calculator;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import jscl.math.Generic;
import jscl.math.function.Constant;
import org.achartengine.ChartFactory;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.about.CalculatorAboutTabActivity;
import org.solovyev.android.calculator.help.CalculatorHelpTabActivity;
import org.solovyev.android.calculator.history.CalculatorHistoryFragmentActivity;
import org.solovyev.android.calculator.math.edit.CalculatorFunctionsFragmentActivity;
import org.solovyev.android.calculator.math.edit.CalculatorOperatorsFragment;
import org.solovyev.android.calculator.math.edit.CalculatorVarsFragment;
import org.solovyev.android.calculator.math.edit.CalculatorVarsFragmentActivity;
import org.solovyev.android.calculator.plot.CalculatorPlotActivity;
import org.solovyev.common.text.StringUtils;
/**
* User: serso
* Date: 11/2/11
* Time: 2:18 PM
*/
public class CalculatorActivityLauncher {
public static void showHistory(@NotNull final Context context) {
context.startActivity(new Intent(context, CalculatorHistoryFragmentActivity.class));
}
public static void showHelp(@NotNull final Context context) {
context.startActivity(new Intent(context, CalculatorHelpTabActivity.class));
}
public static void showSettings(@NotNull final Context context) {
context.startActivity(new Intent(context, CalculatorPreferencesActivity.class));
}
public static void showAbout(@NotNull final Context context) {
context.startActivity(new Intent(context, CalculatorAboutTabActivity.class));
}
public static void showFunctions(@NotNull final Context context) {
context.startActivity(new Intent(context, CalculatorFunctionsFragmentActivity.class));
}
public static void showOperators(@NotNull final Context context) {
context.startActivity(new Intent(context, CalculatorOperatorsFragment.class));
}
public static void showVars(@NotNull final Context context) {
context.startActivity(new Intent(context, CalculatorVarsFragmentActivity.class));
}
public static void plotGraph(@NotNull final Context context, @NotNull Generic generic, @NotNull Constant constant){
final Intent intent = new Intent();
intent.putExtra(ChartFactory.TITLE, context.getString(R.string.c_graph));
intent.putExtra(CalculatorPlotActivity.INPUT, new CalculatorPlotActivity.Input(generic.toString(), constant.getName()));
intent.setClass(context, CalculatorPlotActivity.class);
context.startActivity(intent);
}
public static void createVar(@NotNull final Context context, @NotNull CalculatorDisplay calculatorDisplay) {
final CalculatorDisplayViewState viewState = calculatorDisplay.getViewState();
if (viewState.isValid() ) {
final String varValue = viewState.getText();
if (!StringUtils.isEmpty(varValue)) {
if (CalculatorVarsFragment.isValidValue(varValue)) {
final Intent intent = new Intent(context, CalculatorVarsFragmentActivity.class);
intent.putExtra(CalculatorVarsFragment.CREATE_VAR_EXTRA_STRING, varValue);
context.startActivity(intent);
} else {
Toast.makeText(context, R.string.c_not_valid_result, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, R.string.c_empty_var_error, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, R.string.c_not_valid_result, Toast.LENGTH_SHORT).show();
}
}
}

View File

@@ -1,28 +1,30 @@
package org.solovyev.android.calculator;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.TextView;
import org.jetbrains.annotations.NotNull;
/**
* User: serso
* Date: 9/26/12
* Time: 10:14 PM
*/
public class CalculatorFragmentHelperImpl implements CalculatorFragmentHelper {
@Override
public boolean isPane(@NotNull Fragment fragment) {
return fragment.getActivity() instanceof CalculatorActivity;
}
public void setPaneTitle(@NotNull Fragment fragment, int titleResId) {
final TextView fragmentTitle = (TextView) fragment.getView().findViewById(R.id.fragmentTitle);
if (!isPane(fragment)) {
fragmentTitle.setVisibility(View.GONE);
} else {
fragmentTitle.setText(fragment.getString(titleResId).toUpperCase());
}
}
}
package org.solovyev.android.calculator;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.TextView;
import org.jetbrains.annotations.NotNull;
/**
* User: serso
* Date: 9/26/12
* Time: 10:14 PM
*/
public class CalculatorFragmentHelperImpl implements CalculatorFragmentHelper {
@Override
public boolean isPane(@NotNull Fragment fragment) {
return fragment.getActivity() instanceof CalculatorActivity;
}
public void setPaneTitle(@NotNull Fragment fragment, int titleResId) {
final TextView fragmentTitle = (TextView) fragment.getView().findViewById(R.id.fragmentTitle);
if (fragmentTitle != null) {
if (!isPane(fragment)) {
fragmentTitle.setVisibility(View.GONE);
} else {
fragmentTitle.setText(fragment.getString(titleResId).toUpperCase());
}
}
}
}

View File

@@ -1,321 +1,321 @@
/*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com
* or visit http://se.solovyev.org
*/
package org.solovyev.android.calculator.math.edit;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.actionbarsherlock.app.SherlockListFragment;
import com.google.ads.AdView;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.ads.AdsController;
import org.solovyev.android.calculator.*;
import org.solovyev.android.menu.AMenuBuilder;
import org.solovyev.android.menu.LabeledMenuItem;
import org.solovyev.android.menu.MenuImpl;
import org.solovyev.common.equals.EqualsTool;
import org.solovyev.common.filter.Filter;
import org.solovyev.common.filter.FilterRule;
import org.solovyev.common.math.MathEntity;
import org.solovyev.common.text.StringUtils;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* User: serso
* Date: 12/21/11
* Time: 9:24 PM
*/
public abstract class AbstractMathEntityListFragment<T extends MathEntity> extends SherlockListFragment {
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
public static final String MATH_ENTITY_CATEGORY_EXTRA_STRING = "org.solovyev.android.calculator.CalculatorVarsActivity_math_entity_category";
protected final static List<Character> acceptableChars = Arrays.asList(StringUtils.toObject("1234567890abcdefghijklmnopqrstuvwxyzйцукенгшщзхъфывапролджэячсмитьбюё_".toCharArray()));
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
@Nullable
private MathEntityArrayAdapter<T> adapter;
@Nullable
private String category;
@Nullable
private AdView adView;
@NotNull
private CalculatorFragmentHelper fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper();
protected int getLayoutResId() {
return R.layout.math_entities;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Bundle bundle = getArguments();
if ( bundle != null ) {
category = bundle.getString(MATH_ENTITY_CATEGORY_EXTRA_STRING);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(getLayoutResId(), container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.fragmentHelper.setPaneTitle(this, getTitleResId());
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent,
final View view,
final int position,
final long id) {
CalculatorLocatorImpl.getInstance().getKeyboard().digitButtonPressed(((MathEntity) parent.getItemAtPosition(position)).getName());
}
});
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
final T item = (T) parent.getItemAtPosition(position);
final List<LabeledMenuItem<T>> menuItems = getMenuItemsOnLongClick(item);
if (!menuItems.isEmpty()) {
final AMenuBuilder<LabeledMenuItem<T>, T> menuBuilder = AMenuBuilder.newInstance(AbstractMathEntityListFragment.this.getActivity(), MenuImpl.newInstance(menuItems));
menuBuilder.create(item).show();
}
return true;
}
});
adView = AdsController.getInstance().inflateAd(this.getActivity(), (ViewGroup)view.findViewById(R.id.ad_parent_view), R.id.ad_parent_view);
}
protected abstract int getTitleResId();
@Override
public void onDestroy() {
if (this.adView != null) {
this.adView.destroy();
}
super.onDestroy();
}
@NotNull
protected abstract List<LabeledMenuItem<T>> getMenuItemsOnLongClick(@NotNull T item);
@Override
public void onResume() {
super.onResume();
adapter = new MathEntityArrayAdapter<T>(getDescriptionGetter(), this.getActivity(), R.layout.math_entity, R.id.math_entity_text, getMathEntitiesByCategory());
setListAdapter(adapter);
sort();
}
@NotNull
private List<T> getMathEntitiesByCategory() {
final List<T> result = getMathEntities();
new Filter<T>(new FilterRule<T>() {
@Override
public boolean isFiltered(T t) {
return !isInCategory(t);
}
}).filter(result.iterator());
return result;
}
protected boolean isInCategory(@Nullable T t) {
return t != null && EqualsTool.areEqual(getMathEntityCategory(t), category);
}
@NotNull
protected abstract MathEntityDescriptionGetter getDescriptionGetter();
@NotNull
protected abstract List<T> getMathEntities();
@Nullable
abstract String getMathEntityCategory(@NotNull T t);
protected void sort() {
final MathEntityArrayAdapter<T> localAdapter = adapter;
if (localAdapter != null) {
localAdapter.sort(new Comparator<T>() {
@Override
public int compare(T function1, T function2) {
return function1.getName().compareTo(function2.getName());
}
});
localAdapter.notifyDataSetChanged();
}
}
protected static class MathEntityArrayAdapter<T extends MathEntity> extends ArrayAdapter<T> {
@NotNull
private final MathEntityDescriptionGetter descriptionGetter;
private MathEntityArrayAdapter(@NotNull MathEntityDescriptionGetter descriptionGetter,
@NotNull Context context,
int resource,
int textViewResourceId,
@NotNull List<T> objects) {
super(context, resource, textViewResourceId, objects);
this.descriptionGetter = descriptionGetter;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewGroup result = (ViewGroup) super.getView(position, convertView, parent);
final T mathEntity = getItem(position);
final String mathEntityDescription = descriptionGetter.getDescription(getContext(), mathEntity.getName());
if (!StringUtils.isEmpty(mathEntityDescription)) {
TextView description = (TextView) result.findViewById(R.id.math_entity_description);
if (description == null) {
final LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
final ViewGroup itemView = (ViewGroup) layoutInflater.inflate(R.layout.math_entity, null);
description = (TextView) itemView.findViewById(R.id.math_entity_description);
itemView.removeView(description);
result.addView(description);
}
description.setText(mathEntityDescription);
} else {
TextView description = (TextView) result.findViewById(R.id.math_entity_description);
if (description != null) {
result.removeView(description);
}
}
return result;
}
}
protected static class MathEntityDescriptionGetterImpl implements MathEntityDescriptionGetter {
@NotNull
private final CalculatorMathRegistry<?> mathRegistry;
public MathEntityDescriptionGetterImpl(@NotNull CalculatorMathRegistry<?> mathRegistry) {
this.mathRegistry = mathRegistry;
}
@Override
public String getDescription(@NotNull Context context, @NotNull String mathEntityName) {
return this.mathRegistry.getDescription(mathEntityName);
}
}
protected static interface MathEntityDescriptionGetter {
@Nullable
String getDescription(@NotNull Context context, @NotNull String mathEntityName);
}
public void addToAdapter(@NotNull T mathEntity) {
if (this.adapter != null) {
this.adapter.add(mathEntity);
}
}
public void removeFromAdapter(@NotNull T mathEntity) {
if (this.adapter != null) {
this.adapter.remove(mathEntity);
}
}
public void notifyAdapter() {
if (this.adapter != null) {
this.adapter.notifyDataSetChanged();
}
}
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
static void createTab(@NotNull Context context,
@NotNull TabHost tabHost,
@NotNull String tabId,
@NotNull String categoryId,
int tabCaptionId,
@NotNull Class<? extends Activity> activityClass,
@Nullable Intent parentIntent) {
TabHost.TabSpec spec;
final Intent intent;
if (parentIntent != null) {
intent = new Intent(parentIntent);
} else {
intent = new Intent();
}
intent.setClass(context, activityClass);
intent.putExtra(MATH_ENTITY_CATEGORY_EXTRA_STRING, categoryId);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec(tabId).setIndicator(context.getString(tabCaptionId)).setContent(intent);
tabHost.addTab(spec);
}
@NotNull
public static Bundle createBundleFor(@NotNull String categoryId) {
final Bundle result = new Bundle(1);
result.putString(MATH_ENTITY_CATEGORY_EXTRA_STRING, categoryId);
return result;
}
}
/*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com
* or visit http://se.solovyev.org
*/
package org.solovyev.android.calculator.math.edit;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.actionbarsherlock.app.SherlockListFragment;
import com.google.ads.AdView;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.ads.AdsController;
import org.solovyev.android.calculator.*;
import org.solovyev.android.menu.AMenuBuilder;
import org.solovyev.android.menu.LabeledMenuItem;
import org.solovyev.android.menu.MenuImpl;
import org.solovyev.common.equals.EqualsTool;
import org.solovyev.common.filter.Filter;
import org.solovyev.common.filter.FilterRule;
import org.solovyev.common.math.MathEntity;
import org.solovyev.common.text.StringUtils;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* User: serso
* Date: 12/21/11
* Time: 9:24 PM
*/
public abstract class AbstractMathEntityListFragment<T extends MathEntity> extends SherlockListFragment {
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
public static final String MATH_ENTITY_CATEGORY_EXTRA_STRING = "org.solovyev.android.calculator.CalculatorVarsActivity_math_entity_category";
protected final static List<Character> acceptableChars = Arrays.asList(StringUtils.toObject("1234567890abcdefghijklmnopqrstuvwxyzйцукенгшщзхъфывапролджэячсмитьбюё_".toCharArray()));
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
@Nullable
private MathEntityArrayAdapter<T> adapter;
@Nullable
private String category;
@Nullable
private AdView adView;
@NotNull
private CalculatorFragmentHelper fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper();
protected int getLayoutResId() {
return R.layout.math_entities;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Bundle bundle = getArguments();
if ( bundle != null ) {
category = bundle.getString(MATH_ENTITY_CATEGORY_EXTRA_STRING);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(getLayoutResId(), container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.fragmentHelper.setPaneTitle(this, getTitleResId());
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent,
final View view,
final int position,
final long id) {
CalculatorLocatorImpl.getInstance().getKeyboard().digitButtonPressed(((MathEntity) parent.getItemAtPosition(position)).getName());
}
});
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
final T item = (T) parent.getItemAtPosition(position);
final List<LabeledMenuItem<T>> menuItems = getMenuItemsOnLongClick(item);
if (!menuItems.isEmpty()) {
final AMenuBuilder<LabeledMenuItem<T>, T> menuBuilder = AMenuBuilder.newInstance(AbstractMathEntityListFragment.this.getActivity(), MenuImpl.newInstance(menuItems));
menuBuilder.create(item).show();
}
return true;
}
});
adView = AdsController.getInstance().inflateAd(this.getActivity(), (ViewGroup)view.findViewById(R.id.ad_parent_view), R.id.ad_parent_view);
}
protected abstract int getTitleResId();
@Override
public void onDestroy() {
if (this.adView != null) {
this.adView.destroy();
}
super.onDestroy();
}
@NotNull
protected abstract List<LabeledMenuItem<T>> getMenuItemsOnLongClick(@NotNull T item);
@Override
public void onResume() {
super.onResume();
adapter = new MathEntityArrayAdapter<T>(getDescriptionGetter(), this.getActivity(), R.layout.math_entity, R.id.math_entity_text, getMathEntitiesByCategory());
setListAdapter(adapter);
sort();
}
@NotNull
private List<T> getMathEntitiesByCategory() {
final List<T> result = getMathEntities();
new Filter<T>(new FilterRule<T>() {
@Override
public boolean isFiltered(T t) {
return !isInCategory(t);
}
}).filter(result.iterator());
return result;
}
protected boolean isInCategory(@Nullable T t) {
return t != null && (category == null || EqualsTool.areEqual(getMathEntityCategory(t), category));
}
@NotNull
protected abstract MathEntityDescriptionGetter getDescriptionGetter();
@NotNull
protected abstract List<T> getMathEntities();
@Nullable
abstract String getMathEntityCategory(@NotNull T t);
protected void sort() {
final MathEntityArrayAdapter<T> localAdapter = adapter;
if (localAdapter != null) {
localAdapter.sort(new Comparator<T>() {
@Override
public int compare(T function1, T function2) {
return function1.getName().compareTo(function2.getName());
}
});
localAdapter.notifyDataSetChanged();
}
}
protected static class MathEntityArrayAdapter<T extends MathEntity> extends ArrayAdapter<T> {
@NotNull
private final MathEntityDescriptionGetter descriptionGetter;
private MathEntityArrayAdapter(@NotNull MathEntityDescriptionGetter descriptionGetter,
@NotNull Context context,
int resource,
int textViewResourceId,
@NotNull List<T> objects) {
super(context, resource, textViewResourceId, objects);
this.descriptionGetter = descriptionGetter;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewGroup result = (ViewGroup) super.getView(position, convertView, parent);
final T mathEntity = getItem(position);
final String mathEntityDescription = descriptionGetter.getDescription(getContext(), mathEntity.getName());
if (!StringUtils.isEmpty(mathEntityDescription)) {
TextView description = (TextView) result.findViewById(R.id.math_entity_description);
if (description == null) {
final LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
final ViewGroup itemView = (ViewGroup) layoutInflater.inflate(R.layout.math_entity, null);
description = (TextView) itemView.findViewById(R.id.math_entity_description);
itemView.removeView(description);
result.addView(description);
}
description.setText(mathEntityDescription);
} else {
TextView description = (TextView) result.findViewById(R.id.math_entity_description);
if (description != null) {
result.removeView(description);
}
}
return result;
}
}
protected static class MathEntityDescriptionGetterImpl implements MathEntityDescriptionGetter {
@NotNull
private final CalculatorMathRegistry<?> mathRegistry;
public MathEntityDescriptionGetterImpl(@NotNull CalculatorMathRegistry<?> mathRegistry) {
this.mathRegistry = mathRegistry;
}
@Override
public String getDescription(@NotNull Context context, @NotNull String mathEntityName) {
return this.mathRegistry.getDescription(mathEntityName);
}
}
protected static interface MathEntityDescriptionGetter {
@Nullable
String getDescription(@NotNull Context context, @NotNull String mathEntityName);
}
public void addToAdapter(@NotNull T mathEntity) {
if (this.adapter != null) {
this.adapter.add(mathEntity);
}
}
public void removeFromAdapter(@NotNull T mathEntity) {
if (this.adapter != null) {
this.adapter.remove(mathEntity);
}
}
public void notifyAdapter() {
if (this.adapter != null) {
this.adapter.notifyDataSetChanged();
}
}
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
static void createTab(@NotNull Context context,
@NotNull TabHost tabHost,
@NotNull String tabId,
@NotNull String categoryId,
int tabCaptionId,
@NotNull Class<? extends Activity> activityClass,
@Nullable Intent parentIntent) {
TabHost.TabSpec spec;
final Intent intent;
if (parentIntent != null) {
intent = new Intent(parentIntent);
} else {
intent = new Intent();
}
intent.setClass(context, activityClass);
intent.putExtra(MATH_ENTITY_CATEGORY_EXTRA_STRING, categoryId);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec(tabId).setIndicator(context.getString(tabCaptionId)).setContent(intent);
tabHost.addTab(spec);
}
@NotNull
public static Bundle createBundleFor(@NotNull String categoryId) {
final Bundle result = new Bundle(1);
result.putString(MATH_ENTITY_CATEGORY_EXTRA_STRING, categoryId);
return result;
}
}

View File

@@ -1,234 +1,234 @@
/*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com
* or visit http://se.solovyev.org
*/
package org.solovyev.android.calculator.math.edit;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.ClipboardManager;
import jscl.math.function.Function;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.CalculatorLocatorImpl;
import org.solovyev.android.calculator.R;
import org.solovyev.android.menu.LabeledMenuItem;
import org.solovyev.common.text.StringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* User: serso
* Date: 10/29/11
* Time: 4:55 PM
*/
public class CalculatorFunctionsActivity extends AbstractMathEntityListFragment<Function> {
public static final String CREATE_FUN_EXTRA_STRING = "org.solovyev.android.calculator.math.edit.CalculatorFunctionsTabActivity_create_fun";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
final Function function = (Function) parent.getItemAtPosition(position);
if (function instanceof CustomFunction) {
createEditVariableDialog(CalculatorFunctionsTabActivity.this,
((CustomFunction) function),
function.getName(),
((CustomFunction) function).getContent(),
((CustomFunction) function).getParameterNames(),
null);
}
return true;
}
});*/
/*final Intent intent = getIntent();
if (intent != null) {
final String varValue = intent.getStringExtra(CREATE_FUN_EXTRA_STRING);
if (!StringUtils.isEmpty(varValue)) {
createEditVariableDialog(this, null, null, varValue, null, null);
// in order to stop intent for other tabs
intent.removeExtra(CREATE_FUN_EXTRA_STRING);
}
}*/
}
@Override
protected int getTitleResId() {
return R.string.c_functions;
}
@NotNull
@Override
protected List<LabeledMenuItem<Function>> getMenuItemsOnLongClick(@NotNull Function item) {
List<LabeledMenuItem<Function>> result = new ArrayList<LabeledMenuItem<Function>>(Arrays.asList(LongClickMenuItem.values()));
if ( StringUtils.isEmpty(CalculatorLocatorImpl.getInstance().getEngine().getFunctionsRegistry().getDescription(item.getName())) ) {
result.remove(LongClickMenuItem.copy_description);
}
return result;
}
/* private static void createEditVariableDialog(@NotNull final AbstractMathEntityListActivity<Function> activity,
@Nullable final CustomFunction function,
@Nullable final String name,
@Nullable final String expression,
@Nullable final String[] parameterNames,
@Nullable final String description) {
if (function == null || !function.isSystem()) {
final LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(LAYOUT_INFLATER_SERVICE);
final View editView = layoutInflater.inflate(R.layout.var_edit, null);
final String errorMsg = activity.getString(R.string.c_char_is_not_accepted);
final EditText editName = (EditText) editView.findViewById(R.id.var_edit_name);
editName.setText(name);
editName.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!acceptableChars.contains(c)) {
s.delete(i, i + 1);
Toast.makeText(activity, String.format(errorMsg, c), Toast.LENGTH_SHORT).show();
}
}
}
});
final EditText editValue = (EditText) editView.findViewById(R.id.var_edit_value);
if (!StringUtils.isEmpty(expression)) {
editValue.setText(expression);
}
final EditText editDescription = (EditText) editView.findViewById(R.id.var_edit_description);
editDescription.setText(description);
final CustomFunction.Builder functionBuilder;
if (function != null) {
functionBuilder = new CustomFunction.Builder(function);
} else {
functionBuilder = new CustomFunction.Builder();
}
final AlertDialog.Builder builder = new AlertDialog.Builder(activity)
.setCancelable(true)
.setNegativeButton(R.string.c_cancel, null)
.setPositiveButton(R.string.c_save, new FunctionEditorSaver(functionBuilder, function, editView, activity, CalculatorEngine.instance.getFunctionsRegistry(), new FunctionEditorSaver.EditorCreator<Function>() {
@Override
public void showEditor(@NotNull AbstractMathEntityListActivity<Function> activity, @Nullable CustomFunction editedInstance, @Nullable String name, @Nullable String value, @Nullable String[] parameterNames, @Nullable String description) {
createEditVariableDialog(activity, editedInstance, name, value, parameterNames, description);
}
}))
.setView(editView);
if (function != null) {
// EDIT mode
builder.setTitle(R.string.c_var_edit_var);
builder.setNeutralButton(R.string.c_remove, new MathEntityRemover<Function>(function, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
createEditVariableDialog(activity, function, name, expression, parameterNames, description);
}
}, CalculatorEngine.instance.getFunctionsRegistry(), activity));
} else {
// CREATE mode
builder.setTitle(R.string.c_var_create_var);
}
builder.create().show();
} else {
Toast.makeText(activity, activity.getString(R.string.c_sys_var_cannot_be_changed), Toast.LENGTH_LONG).show();
}
}*/
@NotNull
@Override
protected MathEntityDescriptionGetter getDescriptionGetter() {
return new MathEntityDescriptionGetterImpl(CalculatorLocatorImpl.getInstance().getEngine().getFunctionsRegistry());
}
@NotNull
@Override
protected List<Function> getMathEntities() {
return new ArrayList<Function>(CalculatorLocatorImpl.getInstance().getEngine().getFunctionsRegistry().getEntities());
}
@Override
protected String getMathEntityCategory(@NotNull Function function) {
return CalculatorLocatorImpl.getInstance().getEngine().getFunctionsRegistry().getCategory(function);
}
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
private static enum LongClickMenuItem implements LabeledMenuItem<Function> {
use(R.string.c_use) {
@Override
public void onClick(@NotNull Function data, @NotNull Context context) {
CalculatorLocatorImpl.getInstance().getKeyboard().digitButtonPressed(data.getName());
if (context instanceof Activity) {
((Activity) context).finish();
}
}
},
/*edit(R.string.c_edit) {
@Override
public void doAction(@NotNull Function data, @NotNull Context context) {
if (context instanceof AbstractMathEntityListActivity) {
}
}
},*/
copy_description(R.string.c_copy_description) {
@Override
public void onClick(@NotNull Function data, @NotNull Context context) {
final String text = CalculatorLocatorImpl.getInstance().getEngine().getFunctionsRegistry().getDescription(data.getName());
if (!StringUtils.isEmpty(text)) {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
clipboard.setText(text);
}
}
};
private final int captionId;
LongClickMenuItem(int captionId) {
this.captionId = captionId;
}
@NotNull
@Override
public String getCaption(@NotNull Context context) {
return context.getString(captionId);
}
}
}
/*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com
* or visit http://se.solovyev.org
*/
package org.solovyev.android.calculator.math.edit;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.ClipboardManager;
import jscl.math.function.Function;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.CalculatorLocatorImpl;
import org.solovyev.android.calculator.R;
import org.solovyev.android.menu.LabeledMenuItem;
import org.solovyev.common.text.StringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* User: serso
* Date: 10/29/11
* Time: 4:55 PM
*/
public class CalculatorFunctionsFragment extends AbstractMathEntityListFragment<Function> {
public static final String CREATE_FUN_EXTRA_STRING = "org.solovyev.android.calculator.math.edit.CalculatorFunctionsTabActivity_create_fun";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
final Function function = (Function) parent.getItemAtPosition(position);
if (function instanceof CustomFunction) {
createEditVariableDialog(CalculatorFunctionsTabActivity.this,
((CustomFunction) function),
function.getName(),
((CustomFunction) function).getContent(),
((CustomFunction) function).getParameterNames(),
null);
}
return true;
}
});*/
/*final Intent intent = getIntent();
if (intent != null) {
final String varValue = intent.getStringExtra(CREATE_FUN_EXTRA_STRING);
if (!StringUtils.isEmpty(varValue)) {
createEditVariableDialog(this, null, null, varValue, null, null);
// in order to stop intent for other tabs
intent.removeExtra(CREATE_FUN_EXTRA_STRING);
}
}*/
}
@Override
protected int getTitleResId() {
return R.string.c_functions;
}
@NotNull
@Override
protected List<LabeledMenuItem<Function>> getMenuItemsOnLongClick(@NotNull Function item) {
List<LabeledMenuItem<Function>> result = new ArrayList<LabeledMenuItem<Function>>(Arrays.asList(LongClickMenuItem.values()));
if ( StringUtils.isEmpty(CalculatorLocatorImpl.getInstance().getEngine().getFunctionsRegistry().getDescription(item.getName())) ) {
result.remove(LongClickMenuItem.copy_description);
}
return result;
}
/* private static void createEditVariableDialog(@NotNull final AbstractMathEntityListActivity<Function> activity,
@Nullable final CustomFunction function,
@Nullable final String name,
@Nullable final String expression,
@Nullable final String[] parameterNames,
@Nullable final String description) {
if (function == null || !function.isSystem()) {
final LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(LAYOUT_INFLATER_SERVICE);
final View editView = layoutInflater.inflate(R.layout.var_edit, null);
final String errorMsg = activity.getString(R.string.c_char_is_not_accepted);
final EditText editName = (EditText) editView.findViewById(R.id.var_edit_name);
editName.setText(name);
editName.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!acceptableChars.contains(c)) {
s.delete(i, i + 1);
Toast.makeText(activity, String.format(errorMsg, c), Toast.LENGTH_SHORT).show();
}
}
}
});
final EditText editValue = (EditText) editView.findViewById(R.id.var_edit_value);
if (!StringUtils.isEmpty(expression)) {
editValue.setText(expression);
}
final EditText editDescription = (EditText) editView.findViewById(R.id.var_edit_description);
editDescription.setText(description);
final CustomFunction.Builder functionBuilder;
if (function != null) {
functionBuilder = new CustomFunction.Builder(function);
} else {
functionBuilder = new CustomFunction.Builder();
}
final AlertDialog.Builder builder = new AlertDialog.Builder(activity)
.setCancelable(true)
.setNegativeButton(R.string.c_cancel, null)
.setPositiveButton(R.string.c_save, new FunctionEditorSaver(functionBuilder, function, editView, activity, CalculatorEngine.instance.getFunctionsRegistry(), new FunctionEditorSaver.EditorCreator<Function>() {
@Override
public void showEditor(@NotNull AbstractMathEntityListActivity<Function> activity, @Nullable CustomFunction editedInstance, @Nullable String name, @Nullable String value, @Nullable String[] parameterNames, @Nullable String description) {
createEditVariableDialog(activity, editedInstance, name, value, parameterNames, description);
}
}))
.setView(editView);
if (function != null) {
// EDIT mode
builder.setTitle(R.string.c_var_edit_var);
builder.setNeutralButton(R.string.c_remove, new MathEntityRemover<Function>(function, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
createEditVariableDialog(activity, function, name, expression, parameterNames, description);
}
}, CalculatorEngine.instance.getFunctionsRegistry(), activity));
} else {
// CREATE mode
builder.setTitle(R.string.c_var_create_var);
}
builder.create().show();
} else {
Toast.makeText(activity, activity.getString(R.string.c_sys_var_cannot_be_changed), Toast.LENGTH_LONG).show();
}
}*/
@NotNull
@Override
protected MathEntityDescriptionGetter getDescriptionGetter() {
return new MathEntityDescriptionGetterImpl(CalculatorLocatorImpl.getInstance().getEngine().getFunctionsRegistry());
}
@NotNull
@Override
protected List<Function> getMathEntities() {
return new ArrayList<Function>(CalculatorLocatorImpl.getInstance().getEngine().getFunctionsRegistry().getEntities());
}
@Override
protected String getMathEntityCategory(@NotNull Function function) {
return CalculatorLocatorImpl.getInstance().getEngine().getFunctionsRegistry().getCategory(function);
}
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
private static enum LongClickMenuItem implements LabeledMenuItem<Function> {
use(R.string.c_use) {
@Override
public void onClick(@NotNull Function data, @NotNull Context context) {
CalculatorLocatorImpl.getInstance().getKeyboard().digitButtonPressed(data.getName());
if (context instanceof Activity) {
((Activity) context).finish();
}
}
},
/*edit(R.string.c_edit) {
@Override
public void doAction(@NotNull Function data, @NotNull Context context) {
if (context instanceof AbstractMathEntityListActivity) {
}
}
},*/
copy_description(R.string.c_copy_description) {
@Override
public void onClick(@NotNull Function data, @NotNull Context context) {
final String text = CalculatorLocatorImpl.getInstance().getEngine().getFunctionsRegistry().getDescription(data.getName());
if (!StringUtils.isEmpty(text)) {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
clipboard.setText(text);
}
}
};
private final int captionId;
LongClickMenuItem(int captionId) {
this.captionId = captionId;
}
@NotNull
@Override
public String getCaption(@NotNull Context context) {
return context.getString(captionId);
}
}
}

View File

@@ -1,129 +1,129 @@
package org.solovyev.android.calculator.math.edit;
import android.app.Activity;
import android.content.Context;
import android.text.ClipboardManager;
import jscl.math.operator.Operator;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.CalculatorLocatorImpl;
import org.solovyev.android.calculator.R;
import org.solovyev.android.menu.LabeledMenuItem;
import org.solovyev.common.text.StringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* User: serso
* Date: 11/17/11
* Time: 1:53 PM
*/
public class CalculatorOperatorsActivity extends AbstractMathEntityListFragment<Operator> {
@Override
protected int getTitleResId() {
return R.string.c_operators;
}
@NotNull
@Override
protected List<LabeledMenuItem<Operator>> getMenuItemsOnLongClick(@NotNull Operator item) {
final List<LabeledMenuItem<Operator>> result = new ArrayList<LabeledMenuItem<Operator>>(Arrays.asList(LongClickMenuItem.values()));
if ( StringUtils.isEmpty(OperatorDescriptionGetter.instance.getDescription(this.getActivity(), item.getName())) ) {
result.remove(LongClickMenuItem.copy_description);
}
return result;
}
@NotNull
@Override
protected MathEntityDescriptionGetter getDescriptionGetter() {
return OperatorDescriptionGetter.instance;
}
@NotNull
@Override
protected List<Operator> getMathEntities() {
final List<Operator> result = new ArrayList<Operator>();
result.addAll(CalculatorLocatorImpl.getInstance().getEngine().getOperatorsRegistry().getEntities());
result.addAll(CalculatorLocatorImpl.getInstance().getEngine().getPostfixFunctionsRegistry().getEntities());
return result;
}
@Override
protected String getMathEntityCategory(@NotNull Operator operator) {
String result = CalculatorLocatorImpl.getInstance().getEngine().getOperatorsRegistry().getCategory(operator);
if (result == null) {
result = CalculatorLocatorImpl.getInstance().getEngine().getPostfixFunctionsRegistry().getCategory(operator);
}
return result;
}
private static enum OperatorDescriptionGetter implements MathEntityDescriptionGetter {
instance;
@Override
public String getDescription(@NotNull Context context, @NotNull String mathEntityName) {
String result = CalculatorLocatorImpl.getInstance().getEngine().getOperatorsRegistry().getDescription(mathEntityName);
if (StringUtils.isEmpty(result)) {
result = CalculatorLocatorImpl.getInstance().getEngine().getPostfixFunctionsRegistry().getDescription(mathEntityName);
}
return result;
}
}
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
private static enum LongClickMenuItem implements LabeledMenuItem<Operator> {
use(R.string.c_use) {
@Override
public void onClick(@NotNull Operator data, @NotNull Context context) {
CalculatorLocatorImpl.getInstance().getKeyboard().digitButtonPressed(data.getName());
if (context instanceof Activity) {
((Activity) context).finish();
}
}
},
copy_description(R.string.c_copy_description) {
@Override
public void onClick(@NotNull Operator data, @NotNull Context context) {
final String text = OperatorDescriptionGetter.instance.getDescription(context, data.getName());
if (!StringUtils.isEmpty(text)) {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
clipboard.setText(text);
}
}
};
private final int captionId;
LongClickMenuItem(int captionId) {
this.captionId = captionId;
}
@NotNull
@Override
public String getCaption(@NotNull Context context) {
return context.getString(captionId);
}
}
}
package org.solovyev.android.calculator.math.edit;
import android.app.Activity;
import android.content.Context;
import android.text.ClipboardManager;
import jscl.math.operator.Operator;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.CalculatorLocatorImpl;
import org.solovyev.android.calculator.R;
import org.solovyev.android.menu.LabeledMenuItem;
import org.solovyev.common.text.StringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* User: serso
* Date: 11/17/11
* Time: 1:53 PM
*/
public class CalculatorOperatorsFragment extends AbstractMathEntityListFragment<Operator> {
@Override
protected int getTitleResId() {
return R.string.c_operators;
}
@NotNull
@Override
protected List<LabeledMenuItem<Operator>> getMenuItemsOnLongClick(@NotNull Operator item) {
final List<LabeledMenuItem<Operator>> result = new ArrayList<LabeledMenuItem<Operator>>(Arrays.asList(LongClickMenuItem.values()));
if ( StringUtils.isEmpty(OperatorDescriptionGetter.instance.getDescription(this.getActivity(), item.getName())) ) {
result.remove(LongClickMenuItem.copy_description);
}
return result;
}
@NotNull
@Override
protected MathEntityDescriptionGetter getDescriptionGetter() {
return OperatorDescriptionGetter.instance;
}
@NotNull
@Override
protected List<Operator> getMathEntities() {
final List<Operator> result = new ArrayList<Operator>();
result.addAll(CalculatorLocatorImpl.getInstance().getEngine().getOperatorsRegistry().getEntities());
result.addAll(CalculatorLocatorImpl.getInstance().getEngine().getPostfixFunctionsRegistry().getEntities());
return result;
}
@Override
protected String getMathEntityCategory(@NotNull Operator operator) {
String result = CalculatorLocatorImpl.getInstance().getEngine().getOperatorsRegistry().getCategory(operator);
if (result == null) {
result = CalculatorLocatorImpl.getInstance().getEngine().getPostfixFunctionsRegistry().getCategory(operator);
}
return result;
}
private static enum OperatorDescriptionGetter implements MathEntityDescriptionGetter {
instance;
@Override
public String getDescription(@NotNull Context context, @NotNull String mathEntityName) {
String result = CalculatorLocatorImpl.getInstance().getEngine().getOperatorsRegistry().getDescription(mathEntityName);
if (StringUtils.isEmpty(result)) {
result = CalculatorLocatorImpl.getInstance().getEngine().getPostfixFunctionsRegistry().getDescription(mathEntityName);
}
return result;
}
}
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
private static enum LongClickMenuItem implements LabeledMenuItem<Operator> {
use(R.string.c_use) {
@Override
public void onClick(@NotNull Operator data, @NotNull Context context) {
CalculatorLocatorImpl.getInstance().getKeyboard().digitButtonPressed(data.getName());
if (context instanceof Activity) {
((Activity) context).finish();
}
}
},
copy_description(R.string.c_copy_description) {
@Override
public void onClick(@NotNull Operator data, @NotNull Context context) {
final String text = OperatorDescriptionGetter.instance.getDescription(context, data.getName());
if (!StringUtils.isEmpty(text)) {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
clipboard.setText(text);
}
}
};
private final int captionId;
LongClickMenuItem(int captionId) {
this.captionId = captionId;
}
@NotNull
@Override
public String getCaption(@NotNull Context context) {
return context.getString(captionId);
}
}
}