Fragments

This commit is contained in:
Sergey Solovyev 2012-09-26 21:10:18 +04:00
parent ff1dd19018
commit 5371dbaac1
7 changed files with 1037 additions and 953 deletions

View File

@ -1,31 +1,83 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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
-->
<LinearLayout
xmlns:a="http://schemas.android.com/apk/res/android"
a:layout_width="match_parent"
a:layout_height="match_parent"
a:id="@+id/main_layout"
a:orientation="horizontal"
a:layout_gravity="center"
a:background="@color/default_background"
a:baselineAligned="false">
<include layout="@layout/main_first_pane"
a:layout_height="match_parent"
a:layout_width="0dp"
a:layout_weight="1"/>
<LinearLayout a:id="@+id/main_second_pane"
a:orientation="vertical"
a:layout_height="match_parent"
a:layout_width="0dp"
a:layout_weight="1"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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
-->
<LinearLayout
xmlns:a="http://schemas.android.com/apk/res/android"
a:layout_width="match_parent"
a:layout_height="match_parent"
a:id="@+id/main_layout"
a:orientation="horizontal"
a:layout_gravity="center"
a:background="@color/default_background"
a:baselineAligned="false">
<LinearLayout
a:layout_height="match_parent"
a:layout_width="0dp"
a:layout_weight="1"
a:orientation="vertical"
a:layout_gravity="center">
<LinearLayout a:id="@+id/editorContainer"
a:layout_weight="4"
a:layout_width="match_parent"
a:layout_height="0dp"/>
<LinearLayout a:layout_weight="1"
a:layout_width="match_parent"
a:layout_height="0dp">
<include layout="@layout/calc_left_button"
a:layout_margin="@dimen/button_margin"
a:layout_width="0dp"
a:layout_height="match_parent"
a:layout_weight="1"/>
<include layout="@layout/calc_erase_button"
a:layout_margin="@dimen/button_margin"
a:layout_width="0dp"
a:layout_height="match_parent"
a:layout_weight="1"/>
<LinearLayout a:id="@+id/displayContainer"
a:layout_margin="@dimen/display_margin"
a:layout_weight="4"
a:layout_width="0dp"
a:layout_height="match_parent"/>
<include layout="@layout/calc_clear_button"
a:layout_margin="@dimen/button_margin"
a:layout_width="0dp"
a:layout_height="match_parent"
a:layout_weight="1"/>
<include layout="@layout/calc_right_button"
a:layout_margin="@dimen/button_margin"
a:layout_width="0dp"
a:layout_height="match_parent"
a:layout_weight="1"/>
</LinearLayout>
<LinearLayout a:id="@+id/keyboardContainer"
a:layout_weight="3"
a:layout_width="match_parent"
a:layout_height="0dp"/>
</LinearLayout>
<LinearLayout a:id="@+id/main_second_pane"
a:orientation="vertical"
a:layout_height="match_parent"
a:layout_width="0dp"
a:layout_weight="1"/>
</LinearLayout>

View File

@ -1,381 +1,369 @@
/*
* 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.util.TypedValue;
import android.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.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 = "Calculator++";
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().createCalculatorHistoryHelper(layout.getLayoutId());
activityHelper.onCreate(this, savedInstanceState);
super.onCreate(savedInstanceState);
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.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();
}
/*
**********************************************************************
*
* MENU
*
**********************************************************************
*/
/* @Override
public boolean onPrepareOptionsMenu(Menu menu) {
return this.menu.onPrepareOptionsMenu(this, menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return this.menu.onCreateOptionsMenu(this, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return menu.onOptionsItemSelected(this, item);
}*/
/**
* 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 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);
}
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.util.TypedValue;
import android.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.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().createCalculatorHistoryHelper(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.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,39 +1,44 @@
package org.solovyev.android.calculator;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* User: serso
* Date: 9/25/12
* Time: 10:31 PM
*/
public interface CalculatorActivityHelper {
void onCreate(@NotNull SherlockFragmentActivity activity, @Nullable Bundle savedInstanceState);
void onCreate(@NotNull Activity activity, @Nullable Bundle savedInstanceState);
void onSaveInstanceState(@NotNull SherlockFragmentActivity activity, @NotNull Bundle outState);
void onSaveInstanceState(@NotNull Activity activity, @NotNull Bundle outState);
int getLayoutId();
@NotNull
CalculatorPreferences.Gui.Theme getTheme();
void onResume(@NotNull SherlockFragmentActivity activity);
void onResume(@NotNull Activity activity);
void addTab(@NotNull SherlockFragmentActivity activity,
@NotNull String tag,
@NotNull Class<? extends Fragment> fragmentClass,
@Nullable Bundle fragmentArgs,
int captionResId, int parentViewId);
void restoreSavedTab(@NotNull SherlockFragmentActivity activity);
}
package org.solovyev.android.calculator;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* User: serso
* Date: 9/25/12
* Time: 10:31 PM
*/
public interface CalculatorActivityHelper {
void onCreate(@NotNull SherlockFragmentActivity activity, @Nullable Bundle savedInstanceState);
void onCreate(@NotNull Activity activity, @Nullable Bundle savedInstanceState);
void onSaveInstanceState(@NotNull SherlockFragmentActivity activity, @NotNull Bundle outState);
void onSaveInstanceState(@NotNull Activity activity, @NotNull Bundle outState);
int getLayoutId();
@NotNull
CalculatorPreferences.Gui.Theme getTheme();
void onResume(@NotNull SherlockFragmentActivity activity);
void onResume(@NotNull Activity activity);
void onDestroy(@NotNull SherlockFragmentActivity activity);
void addTab(@NotNull SherlockFragmentActivity activity,
@NotNull String tag,
@NotNull Class<? extends Fragment> fragmentClass,
@Nullable Bundle fragmentArgs,
int captionResId, int parentViewId);
void restoreSavedTab(@NotNull SherlockFragmentActivity activity);
void logDebug(@NotNull String message);
void onPause(@NotNull SherlockFragmentActivity activity);
}

View File

@ -1,152 +1,169 @@
package org.solovyev.android.calculator;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.AndroidUtils;
import org.solovyev.android.fragments.FragmentUtils;
import org.solovyev.android.sherlock.tabs.ActionBarFragmentTabListener;
import java.util.ArrayList;
import java.util.List;
/**
* User: serso
* Date: 9/25/12
* Time: 10:32 PM
*/
public class CalculatorActivityHelperImpl implements CalculatorActivityHelper {
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
private static final String SELECTED_NAV = "selected_nav";
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
private int layoutId;
private boolean homeIcon = false;
@NotNull
private final List<String> fragmentTags = new ArrayList<String>();
@NotNull
private CalculatorPreferences.Gui.Theme theme;
private int navPosition = 0;
public CalculatorActivityHelperImpl(int layoutId) {
this.layoutId = layoutId;
}
public CalculatorActivityHelperImpl(int layoutId, boolean homeIcon) {
this.layoutId = layoutId;
this.homeIcon = homeIcon;
}
@Override
public void onCreate(@NotNull Activity activity, @Nullable Bundle savedInstanceState) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
this.theme = CalculatorPreferences.Gui.getTheme(preferences);
activity.setTheme(this.theme.getThemeId());
activity.setContentView(layoutId);
}
@Override
public void onCreate(@NotNull final SherlockFragmentActivity activity, @Nullable Bundle savedInstanceState) {
this.onCreate((Activity) activity, savedInstanceState);
final ActionBar actionBar = activity.getSupportActionBar();
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(homeIcon);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
if (savedInstanceState != null) {
navPosition = savedInstanceState.getInt(SELECTED_NAV, 0);
}
}
@Override
public void restoreSavedTab(@NotNull SherlockFragmentActivity activity) {
final ActionBar actionBar = activity.getSupportActionBar();
if (navPosition >= 0 && navPosition < actionBar.getTabCount()) {
activity.getSupportActionBar().setSelectedNavigationItem(navPosition);
}
}
@Override
public void onSaveInstanceState(@NotNull SherlockFragmentActivity activity, @NotNull Bundle outState) {
FragmentUtils.detachFragments(activity, fragmentTags);
onSaveInstanceState((Activity) activity, outState);
outState.putInt(SELECTED_NAV, activity.getSupportActionBar().getSelectedNavigationIndex());
}
@Override
public void onSaveInstanceState(@NotNull Activity activity, @NotNull Bundle outState) {
}
@Override
public void onResume(@NotNull Activity activity) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
final CalculatorPreferences.Gui.Theme newTheme = CalculatorPreferences.Gui.theme.getPreference(preferences);
if (!theme.equals(newTheme)) {
AndroidUtils.restartActivity(activity);
}
}
@Override
public void addTab(@NotNull SherlockFragmentActivity activity,
@NotNull String tag,
@NotNull Class<? extends Fragment> fragmentClass,
@Nullable Bundle fragmentArgs,
int captionResId,
int parentViewId) {
activity.getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
final ActionBar actionBar = activity.getSupportActionBar();
final ActionBar.Tab tab = actionBar.newTab();
tab.setTag(tag);
tab.setText(captionResId);
tab.setTabListener(new ActionBarFragmentTabListener(activity, tag, fragmentClass, fragmentArgs, parentViewId));
actionBar.addTab(tab);
fragmentTags.add(tag);
}
@Override
public int getLayoutId() {
return layoutId;
}
@Override
@NotNull
public CalculatorPreferences.Gui.Theme getTheme() {
return theme;
}
@Override
public void onResume(@NotNull SherlockFragmentActivity activity) {
onResume((Activity) activity);
}
}
package org.solovyev.android.calculator;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.AndroidUtils;
import org.solovyev.android.sherlock.tabs.ActionBarFragmentTabListener;
import java.util.ArrayList;
import java.util.List;
/**
* User: serso
* Date: 9/25/12
* Time: 10:32 PM
*/
public class CalculatorActivityHelperImpl implements CalculatorActivityHelper {
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
private static final String SELECTED_NAV = "selected_nav";
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
private int layoutId;
private boolean homeIcon = false;
@NotNull
private final List<String> fragmentTags = new ArrayList<String>();
@NotNull
private CalculatorPreferences.Gui.Theme theme;
private int navPosition = 0;
@NotNull
private String logTag = "CalculatorActivity";
public CalculatorActivityHelperImpl(int layoutId, @NotNull String logTag) {
this.layoutId = layoutId;
this.logTag = logTag;
}
public CalculatorActivityHelperImpl(int layoutId, boolean homeIcon) {
this.layoutId = layoutId;
this.homeIcon = homeIcon;
}
@Override
public void onCreate(@NotNull Activity activity, @Nullable Bundle savedInstanceState) {
Log.d(logTag + ": helper", "onCreate");
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
this.theme = CalculatorPreferences.Gui.getTheme(preferences);
activity.setTheme(this.theme.getThemeId());
activity.setContentView(layoutId);
}
@Override
public void onCreate(@NotNull final SherlockFragmentActivity activity, @Nullable Bundle savedInstanceState) {
this.onCreate((Activity) activity, savedInstanceState);
final ActionBar actionBar = activity.getSupportActionBar();
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(homeIcon);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
if (savedInstanceState != null) {
navPosition = savedInstanceState.getInt(SELECTED_NAV, 0);
}
}
@Override
public void restoreSavedTab(@NotNull SherlockFragmentActivity activity) {
final ActionBar actionBar = activity.getSupportActionBar();
if (navPosition >= 0 && navPosition < actionBar.getTabCount()) {
activity.getSupportActionBar().setSelectedNavigationItem(navPosition);
}
}
@Override
public void logDebug(@NotNull String message) {
Log.d(logTag, message);
}
@Override
public void onSaveInstanceState(@NotNull SherlockFragmentActivity activity, @NotNull Bundle outState) {
onSaveInstanceState((Activity) activity, outState);
outState.putInt(SELECTED_NAV, activity.getSupportActionBar().getSelectedNavigationIndex());
}
@Override
public void onSaveInstanceState(@NotNull Activity activity, @NotNull Bundle outState) {
}
@Override
public void onResume(@NotNull Activity activity) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
final CalculatorPreferences.Gui.Theme newTheme = CalculatorPreferences.Gui.theme.getPreference(preferences);
if (!theme.equals(newTheme)) {
AndroidUtils.restartActivity(activity);
}
}
@Override
public void onDestroy(@NotNull SherlockFragmentActivity activity) {
}
@Override
public void onPause(@NotNull SherlockFragmentActivity activity) {
}
@Override
public void addTab(@NotNull SherlockFragmentActivity activity,
@NotNull String tag,
@NotNull Class<? extends Fragment> fragmentClass,
@Nullable Bundle fragmentArgs,
int captionResId,
int parentViewId) {
activity.getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
final ActionBar actionBar = activity.getSupportActionBar();
final ActionBar.Tab tab = actionBar.newTab();
tab.setTag(tag);
tab.setText(captionResId);
tab.setTabListener(new ActionBarFragmentTabListener(activity, tag, fragmentClass, fragmentArgs, parentViewId));
actionBar.addTab(tab);
fragmentTags.add(tag);
}
@Override
public int getLayoutId() {
return layoutId;
}
@Override
@NotNull
public CalculatorPreferences.Gui.Theme getTheme() {
return theme;
}
@Override
public void onResume(@NotNull SherlockFragmentActivity activity) {
onResume((Activity) activity);
}
}

View File

@ -111,7 +111,7 @@ public class CalculatorApplication extends android.app.Application {
}
@NotNull
public CalculatorActivityHelper createCalculatorHistoryHelper(int layoutResId) {
return new CalculatorActivityHelperImpl(layoutResId);
public CalculatorActivityHelper createCalculatorHistoryHelper(int layoutResId, @NotNull String logTag) {
return new CalculatorActivityHelperImpl(layoutResId, logTag);
}
}

View File

@ -1,285 +1,307 @@
/*
* 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.history;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
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.calculator.jscl.JsclOperation;
import org.solovyev.android.menu.AMenuBuilder;
import org.solovyev.android.menu.MenuImpl;
import org.solovyev.common.collections.CollectionsUtils;
import org.solovyev.common.equals.Equalizer;
import org.solovyev.common.filter.Filter;
import org.solovyev.common.filter.FilterRule;
import org.solovyev.common.filter.FilterRulesChain;
import org.solovyev.common.text.StringUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* User: serso
* Date: 10/15/11
* Time: 1:13 PM
*/
public abstract class AbstractCalculatorHistoryFragment extends SherlockListFragment implements CalculatorEventListener {
public static final Comparator<CalculatorHistoryState> COMPARATOR = new Comparator<CalculatorHistoryState>() {
@Override
public int compare(CalculatorHistoryState state1, CalculatorHistoryState state2) {
if (state1.isSaved() == state2.isSaved()) {
long l = state2.getTime() - state1.getTime();
return l > 0l ? 1 : (l < 0l ? -1 : 0);
} else if (state1.isSaved()) {
return -1;
} else if (state2.isSaved()) {
return 1;
}
return 0;
}
};
@NotNull
private ArrayAdapter<CalculatorHistoryState> adapter;
@Nullable
private AdView adView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.history_fragment, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
adapter = new HistoryArrayAdapter(this.getActivity(), getItemLayoutId(), R.id.history_item, new ArrayList<CalculatorHistoryState>());
setListAdapter(adapter);
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) {
useHistoryItem((CalculatorHistoryState) parent.getItemAtPosition(position));
}
});
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
final CalculatorHistoryState historyState = (CalculatorHistoryState) parent.getItemAtPosition(position);
final Context context = getActivity();
final HistoryItemMenuData data = new HistoryItemMenuData(historyState, adapter);
final List<HistoryItemMenuItem> menuItems = CollectionsUtils.asList(HistoryItemMenuItem.values());
if (historyState.isSaved()) {
menuItems.remove(HistoryItemMenuItem.save);
} else {
if (isAlreadySaved(historyState)) {
menuItems.remove(HistoryItemMenuItem.save);
}
menuItems.remove(HistoryItemMenuItem.remove);
menuItems.remove(HistoryItemMenuItem.edit);
}
if (historyState.getDisplayState().isValid() && StringUtils.isEmpty(historyState.getDisplayState().getEditorState().getText())) {
menuItems.remove(HistoryItemMenuItem.copy_result);
}
final AMenuBuilder<HistoryItemMenuItem, HistoryItemMenuData> menuBuilder = AMenuBuilder.newInstance(context, MenuImpl.newInstance(menuItems));
menuBuilder.create(data).show();
return true;
}
});
adView = AdsController.getInstance().inflateAd(this.getActivity(), (ViewGroup)view.findViewById(R.id.ad_parent_view), R.id.ad_parent_view);
}
@Override
public void onDestroy() {
if ( this.adView != null ) {
this.adView.destroy();
}
super.onDestroy();
}
protected abstract int getItemLayoutId();
@Override
public void onResume() {
super.onResume();
CalculatorLocatorImpl.getInstance().getCalculator().addCalculatorEventListener(this);
updateAdapter();
}
@Override
public void onPause() {
super.onPause();
CalculatorLocatorImpl.getInstance().getCalculator().removeCalculatorEventListener(this);
}
private void updateAdapter() {
final List<CalculatorHistoryState> historyList = getHistoryList();
final ArrayAdapter<CalculatorHistoryState> adapter = getAdapter();
try {
adapter.setNotifyOnChange(false);
adapter.clear();
for (CalculatorHistoryState historyState : historyList) {
adapter.add(historyState);
}
} finally {
adapter.setNotifyOnChange(true);
}
adapter.notifyDataSetChanged();
}
public static boolean isAlreadySaved(@NotNull CalculatorHistoryState historyState) {
assert !historyState.isSaved();
boolean result = false;
try {
historyState.setSaved(true);
if ( CollectionsUtils.contains(historyState, CalculatorLocatorImpl.getInstance().getHistory().getSavedHistory(), new Equalizer<CalculatorHistoryState>() {
@Override
public boolean equals(@Nullable CalculatorHistoryState first, @Nullable CalculatorHistoryState second) {
return first != null && second != null &&
first.getTime() == second.getTime() &&
first.getDisplayState().equals(second.getDisplayState()) &&
first.getEditorState().equals(second.getEditorState());
}
}) ) {
result = true;
}
} finally {
historyState.setSaved(false);
}
return result;
}
public static void useHistoryItem(@NotNull final CalculatorHistoryState historyState) {
CalculatorLocatorImpl.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.use_history_state, historyState);
}
@NotNull
private List<CalculatorHistoryState> getHistoryList() {
final List<CalculatorHistoryState> calculatorHistoryStates = getHistoryItems();
Collections.sort(calculatorHistoryStates, COMPARATOR);
final FilterRulesChain<CalculatorHistoryState> filterRulesChain = new FilterRulesChain<CalculatorHistoryState>();
filterRulesChain.addFilterRule(new FilterRule<CalculatorHistoryState>() {
@Override
public boolean isFiltered(CalculatorHistoryState object) {
return object == null || StringUtils.isEmpty(object.getEditorState().getText());
}
});
new Filter<CalculatorHistoryState>(filterRulesChain).filter(calculatorHistoryStates.iterator());
return calculatorHistoryStates;
}
@NotNull
protected abstract List<CalculatorHistoryState> getHistoryItems();
@NotNull
public static String getHistoryText(@NotNull CalculatorHistoryState state) {
final StringBuilder result = new StringBuilder();
result.append(state.getEditorState().getText());
result.append(getIdentitySign(state.getDisplayState().getJsclOperation()));
final String expressionResult = state.getDisplayState().getEditorState().getText();
if (expressionResult != null) {
result.append(expressionResult);
}
return result.toString();
}
@NotNull
private static String getIdentitySign(@NotNull JsclOperation jsclOperation) {
return jsclOperation == JsclOperation.simplify ? "" : "=";
}
// todo serso: menu
/* @Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
final MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.history_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean result;
switch (item.getItemId()) {
case R.id.history_menu_clear_history:
clearHistory();
result = true;
break;
default:
result = super.onOptionsItemSelected(item);
}
return result;
}*/
protected abstract void clearHistory();
@NotNull
protected ArrayAdapter<CalculatorHistoryState> getAdapter() {
return adapter;
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
if ( calculatorEventType == CalculatorEventType.history_state_added ) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
updateAdapter();
}
});
}
}
}
/*
* 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.history;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
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.calculator.jscl.JsclOperation;
import org.solovyev.android.menu.AMenuBuilder;
import org.solovyev.android.menu.MenuImpl;
import org.solovyev.common.collections.CollectionsUtils;
import org.solovyev.common.equals.Equalizer;
import org.solovyev.common.filter.Filter;
import org.solovyev.common.filter.FilterRule;
import org.solovyev.common.filter.FilterRulesChain;
import org.solovyev.common.text.StringUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* User: serso
* Date: 10/15/11
* Time: 1:13 PM
*/
public abstract class AbstractCalculatorHistoryFragment extends SherlockListFragment implements CalculatorEventListener {
@NotNull
private static final String TAG = "CalculatorHistoryFragment";
public static final Comparator<CalculatorHistoryState> COMPARATOR = new Comparator<CalculatorHistoryState>() {
@Override
public int compare(CalculatorHistoryState state1, CalculatorHistoryState state2) {
if (state1.isSaved() == state2.isSaved()) {
long l = state2.getTime() - state1.getTime();
return l > 0l ? 1 : (l < 0l ? -1 : 0);
} else if (state1.isSaved()) {
return -1;
} else if (state2.isSaved()) {
return 1;
}
return 0;
}
};
@NotNull
private ArrayAdapter<CalculatorHistoryState> adapter;
@Nullable
private AdView adView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
logDebug("onCreate");
}
private int logDebug(@NotNull String msg) {
return Log.d(TAG + ": " + getTag(), msg);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View result = inflater.inflate(R.layout.history_fragment, container, false);
logDebug("onCreateView");
return result;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
logDebug("onViewCreated");
adapter = new HistoryArrayAdapter(this.getActivity(), getItemLayoutId(), R.id.history_item, new ArrayList<CalculatorHistoryState>());
setListAdapter(adapter);
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) {
useHistoryItem((CalculatorHistoryState) parent.getItemAtPosition(position));
}
});
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
final CalculatorHistoryState historyState = (CalculatorHistoryState) parent.getItemAtPosition(position);
final Context context = getActivity();
final HistoryItemMenuData data = new HistoryItemMenuData(historyState, adapter);
final List<HistoryItemMenuItem> menuItems = CollectionsUtils.asList(HistoryItemMenuItem.values());
if (historyState.isSaved()) {
menuItems.remove(HistoryItemMenuItem.save);
} else {
if (isAlreadySaved(historyState)) {
menuItems.remove(HistoryItemMenuItem.save);
}
menuItems.remove(HistoryItemMenuItem.remove);
menuItems.remove(HistoryItemMenuItem.edit);
}
if (historyState.getDisplayState().isValid() && StringUtils.isEmpty(historyState.getDisplayState().getEditorState().getText())) {
menuItems.remove(HistoryItemMenuItem.copy_result);
}
final AMenuBuilder<HistoryItemMenuItem, HistoryItemMenuData> menuBuilder = AMenuBuilder.newInstance(context, MenuImpl.newInstance(menuItems));
menuBuilder.create(data).show();
return true;
}
});
adView = AdsController.getInstance().inflateAd(this.getActivity(), (ViewGroup)view.findViewById(R.id.ad_parent_view), R.id.ad_parent_view);
}
@Override
public void onDestroy() {
logDebug("onDestroy");
if ( this.adView != null ) {
this.adView.destroy();
}
super.onDestroy();
}
protected abstract int getItemLayoutId();
@Override
public void onResume() {
logDebug("onResume");
super.onResume();
CalculatorLocatorImpl.getInstance().getCalculator().addCalculatorEventListener(this);
updateAdapter();
}
@Override
public void onPause() {
logDebug("onPause");
super.onPause();
CalculatorLocatorImpl.getInstance().getCalculator().removeCalculatorEventListener(this);
}
private void updateAdapter() {
final List<CalculatorHistoryState> historyList = getHistoryList();
final ArrayAdapter<CalculatorHistoryState> adapter = getAdapter();
try {
adapter.setNotifyOnChange(false);
adapter.clear();
for (CalculatorHistoryState historyState : historyList) {
adapter.add(historyState);
}
} finally {
adapter.setNotifyOnChange(true);
}
adapter.notifyDataSetChanged();
}
public static boolean isAlreadySaved(@NotNull CalculatorHistoryState historyState) {
assert !historyState.isSaved();
boolean result = false;
try {
historyState.setSaved(true);
if ( CollectionsUtils.contains(historyState, CalculatorLocatorImpl.getInstance().getHistory().getSavedHistory(), new Equalizer<CalculatorHistoryState>() {
@Override
public boolean equals(@Nullable CalculatorHistoryState first, @Nullable CalculatorHistoryState second) {
return first != null && second != null &&
first.getTime() == second.getTime() &&
first.getDisplayState().equals(second.getDisplayState()) &&
first.getEditorState().equals(second.getEditorState());
}
}) ) {
result = true;
}
} finally {
historyState.setSaved(false);
}
return result;
}
public static void useHistoryItem(@NotNull final CalculatorHistoryState historyState) {
CalculatorLocatorImpl.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.use_history_state, historyState);
}
@NotNull
private List<CalculatorHistoryState> getHistoryList() {
final List<CalculatorHistoryState> calculatorHistoryStates = getHistoryItems();
Collections.sort(calculatorHistoryStates, COMPARATOR);
final FilterRulesChain<CalculatorHistoryState> filterRulesChain = new FilterRulesChain<CalculatorHistoryState>();
filterRulesChain.addFilterRule(new FilterRule<CalculatorHistoryState>() {
@Override
public boolean isFiltered(CalculatorHistoryState object) {
return object == null || StringUtils.isEmpty(object.getEditorState().getText());
}
});
new Filter<CalculatorHistoryState>(filterRulesChain).filter(calculatorHistoryStates.iterator());
return calculatorHistoryStates;
}
@NotNull
protected abstract List<CalculatorHistoryState> getHistoryItems();
@NotNull
public static String getHistoryText(@NotNull CalculatorHistoryState state) {
final StringBuilder result = new StringBuilder();
result.append(state.getEditorState().getText());
result.append(getIdentitySign(state.getDisplayState().getJsclOperation()));
final String expressionResult = state.getDisplayState().getEditorState().getText();
if (expressionResult != null) {
result.append(expressionResult);
}
return result.toString();
}
@NotNull
private static String getIdentitySign(@NotNull JsclOperation jsclOperation) {
return jsclOperation == JsclOperation.simplify ? "" : "=";
}
// todo serso: menu
/* @Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
final MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.history_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean result;
switch (item.getItemId()) {
case R.id.history_menu_clear_history:
clearHistory();
result = true;
break;
default:
result = super.onOptionsItemSelected(item);
}
return result;
}*/
protected abstract void clearHistory();
@NotNull
protected ArrayAdapter<CalculatorHistoryState> getAdapter() {
return adapter;
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
if ( calculatorEventType == CalculatorEventType.history_state_added ) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
logDebug("onCalculatorEvent");
updateAdapter();
}
});
}
}
}

View File

@ -1,64 +1,64 @@
/*
* 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.history;
import android.os.Bundle;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.*;
/**
* User: serso
* Date: 12/18/11
* Time: 7:37 PM
*/
public class CalculatorHistoryFragmentActivity extends SherlockFragmentActivity implements CalculatorEventListener {
@NotNull
private final CalculatorActivityHelper activityHelper = CalculatorApplication.getInstance().createCalculatorHistoryHelper(R.layout.main_empty);
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityHelper.onCreate(this, savedInstanceState);
activityHelper.addTab(this, "history", CalculatorHistoryFragment.class, null, R.string.c_history, R.id.main_layout);
activityHelper.addTab(this, "saved_history", CalculatorSavedHistoryFragment.class, null, R.string.c_saved_history, R.id.main_layout);
CalculatorLocatorImpl.getInstance().getCalculator().addCalculatorEventListener(this);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
activityHelper.onSaveInstanceState(this, outState);
}
@Override
protected void onResume() {
super.onResume();
activityHelper.onResume(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
CalculatorLocatorImpl.getInstance().getCalculator().removeCalculatorEventListener(this);
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
if ( calculatorEventType == CalculatorEventType.use_history_state ) {
this.finish();
}
}
}
/*
* 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.history;
import android.os.Bundle;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.*;
/**
* User: serso
* Date: 12/18/11
* Time: 7:37 PM
*/
public class CalculatorHistoryFragmentActivity extends SherlockFragmentActivity implements CalculatorEventListener {
@NotNull
private final CalculatorActivityHelper activityHelper = CalculatorApplication.getInstance().createCalculatorHistoryHelper(R.layout.main_empty, CalculatorHistoryFragmentActivity.class.getSimpleName());
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityHelper.onCreate(this, savedInstanceState);
activityHelper.addTab(this, "history", CalculatorHistoryFragment.class, null, R.string.c_history, R.id.main_layout);
activityHelper.addTab(this, "saved_history", CalculatorSavedHistoryFragment.class, null, R.string.c_saved_history, R.id.main_layout);
CalculatorLocatorImpl.getInstance().getCalculator().addCalculatorEventListener(this);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
activityHelper.onSaveInstanceState(this, outState);
}
@Override
protected void onResume() {
super.onResume();
activityHelper.onResume(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
CalculatorLocatorImpl.getInstance().getCalculator().removeCalculatorEventListener(this);
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
if ( calculatorEventType == CalculatorEventType.use_history_state ) {
this.finish();
}
}
}