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,66 +1,66 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto" android:versionCode="81" android:versionName="1.3.2" <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto" android:versionCode="81" android:versionName="1.3.2"
package="org.solovyev.android.calculator"> package="org.solovyev.android.calculator">
<uses-permission android:name="android.permission.VIBRATE"/> <uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="com.android.vending.BILLING"/> <uses-permission android:name="com.android.vending.BILLING"/>
<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="8"/> <uses-sdk android:minSdkVersion="4" android:targetSdkVersion="8"/>
<application android:debuggable="true" android:hardwareAccelerated="false" android:icon="@drawable/icon" android:label="@string/c_app_name" android:name=".CalculatorApplication" android:theme="@style/metro_blue_theme"> <application android:debuggable="true" android:hardwareAccelerated="false" android:icon="@drawable/icon" android:label="@string/c_app_name" android:name=".CalculatorApplication" android:theme="@style/metro_blue_theme">
<activity android:label="@string/c_app_name" android:name=".CalculatorActivity" android:windowSoftInputMode="adjustPan"> <activity android:label="@string/c_app_name" android:name=".CalculatorActivity" android:windowSoftInputMode="adjustPan">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN"/> <action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/> <category android:name="android.intent.category.LAUNCHER"/>
</intent-filter> </intent-filter>
</activity> </activity>
<!--NOTE: a:configChanges="orientation|keyboardHidden" is needed to correct work of dialog windows (not to close them on orientation change) --> <!--NOTE: a:configChanges="orientation|keyboardHidden" is needed to correct work of dialog windows (not to close them on orientation change) -->
<activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_app_settings" android:name=".CalculatorPreferencesActivity"/> <activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_app_settings" android:name=".CalculatorPreferencesActivity"/>
<activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_history" android:name=".history.CalculatorHistoryFragmentActivity"/> <activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_history" android:name=".history.CalculatorHistoryFragmentActivity"/>
<activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_about" android:name=".about.CalculatorAboutTabActivity"/> <activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_about" android:name=".about.CalculatorAboutTabActivity"/>
<activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_about" android:name=".about.CalculatorAboutActivity"/> <activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_about" android:name=".about.CalculatorAboutActivity"/>
<activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_about" android:name=".about.CalculatorReleaseNotesActivity"/> <activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_about" android:name=".about.CalculatorReleaseNotesActivity"/>
<activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_help" android:name=".help.CalculatorHelpTabActivity"/> <activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_help" android:name=".help.CalculatorHelpTabActivity"/>
<activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_help" android:name=".help.HelpFaqActivity"/> <activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_help" android:name=".help.HelpFaqActivity"/>
<activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_help" android:name=".help.HelpHintsActivity"/> <activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_help" android:name=".help.HelpHintsActivity"/>
<activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_help" android:name=".help.HelpScreensActivity"/> <activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_help" android:name=".help.HelpScreensActivity"/>
<activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_functions" android:name=".math.edit.CalculatorFunctionsFragmentActivity"/> <activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_functions" android:name=".math.edit.CalculatorFunctionsFragmentActivity"/>
<activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_functions" android:name=".math.edit.CalculatorFunctionsActivity"/> <activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_functions" android:name=".math.edit.CalculatorFunctionsFragment"/>
<activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_operators" android:name=".math.edit.CalculatorOperatorsActivity"/> <activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_operators" android:name=".math.edit.CalculatorOperatorsFragment"/>
<activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_vars_and_constants" android:name=".math.edit.CalculatorVarsFragmentActivity"/> <activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_vars_and_constants" android:name=".math.edit.CalculatorVarsFragmentActivity"/>
<activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_vars_and_constants" android:name=".math.edit.CalculatorVarsFragment"/> <activity android:configChanges="orientation|keyboardHidden" android:label="@string/c_vars_and_constants" android:name=".math.edit.CalculatorVarsFragment"/>
<activity android:label="@string/c_plot_graph" android:name=".plot.CalculatorPlotActivity"/> <activity android:label="@string/c_plot_graph" android:name=".plot.CalculatorPlotActivity"/>
<activity android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:name="com.google.ads.AdActivity"/> <activity android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:name="com.google.ads.AdActivity"/>
<service android:name="net.robotmedia.billing.BillingService"/> <service android:name="net.robotmedia.billing.BillingService"/>
<receiver android:name="net.robotmedia.billing.BillingReceiver"> <receiver android:name="net.robotmedia.billing.BillingReceiver">
<intent-filter> <intent-filter>
<action android:name="com.android.vending.billing.IN_APP_NOTIFY"/> <action android:name="com.android.vending.billing.IN_APP_NOTIFY"/>
<action android:name="com.android.vending.billing.RESPONSE_CODE"/> <action android:name="com.android.vending.billing.RESPONSE_CODE"/>
<action android:name="com.android.vending.billing.PURCHASE_STATE_CHANGED"/> <action android:name="com.android.vending.billing.PURCHASE_STATE_CHANGED"/>
</intent-filter> </intent-filter>
</receiver> </receiver>
</application> </application>
</manifest> </manifest>

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/second_pane_background"/>
<corners android:radius="1dp" />
</shape>

View File

@ -1,21 +1,17 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- <LinearLayout xmlns:a="http://schemas.android.com/apk/res/android"
~ Copyright (c) 2009-2011. Created by serso aka se.solovyev. a:orientation="vertical"
~ For more information, please, contact se.solovyev@gmail.com a:id="@+id/ad_parent_view"
~ or visit http://se.solovyev.org style="?fragmentLayoutStyle"
--> a:layout_width="match_parent"
a:layout_height="match_parent">
<LinearLayout xmlns:a="http://schemas.android.com/apk/res/android"
a:orientation="vertical" <TextView a:id="@+id/fragmentTitle"
a:id="@+id/ad_parent_view" a:layout_height="wrap_content"
a:layout_width="fill_parent" a:layout_width="match_parent"
a:layout_height="fill_parent"> style="?fragmentTitleStyle"/>
<ListView <ListView style="?fragmentListViewStyle"/>
a:layout_width="fill_parent"
a:layout_height="fill_parent"
a:layout_weight="1"
a:id="@android:id/list"/>
</LinearLayout> </LinearLayout>

View File

@ -1,66 +1,66 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- <!--
~ Copyright (c) 2009-2011. Created by serso aka se.solovyev. ~ Copyright (c) 2009-2011. Created by serso aka se.solovyev.
~ For more information, please, contact se.solovyev@gmail.com ~ For more information, please, contact se.solovyev@gmail.com
~ or visit http://se.solovyev.org ~ or visit http://se.solovyev.org
--> -->
<resources> <resources>
<style name="default_digit_button_style" parent="button_style"> <style name="default_digit_button_style" parent="button_style">
<item name="android:background">@drawable/default_button</item> <item name="android:background">@drawable/default_button</item>
</style> </style>
<style name="default_control_button_style" parent="button_style"/> <style name="default_control_button_style" parent="button_style"/>
<style name="default_operation_button_style" parent="default_digit_button_style"> <style name="default_operation_button_style" parent="default_digit_button_style">
<item name="android:textColor">@color/button_operator_text_color</item> <item name="android:textColor">@color/button_operator_text_color</item>
</style> </style>
<style name="default_control_image_button_style" parent="default_control_button_style"> <style name="default_control_image_button_style" parent="default_control_button_style">
<item name="android:padding">6dp</item> <item name="android:padding">6dp</item>
</style> </style>
<style name="default_second_pane_style"> <style name="default_second_pane_style">
<item name="android:background">@color/second_pane_background</item> <item name="android:background">@drawable/second_pane_background</item>
<item name="android:layout_margin">5dp</item> <item name="android:layout_margin">5dp</item>
</style> </style>
<style name="default_fragment_list_view_style"> <style name="default_fragment_list_view_style">
<item name="android:id">@android:id/list</item> <item name="android:id">@android:id/list</item>
<item name="android:divider">@null</item> <item name="android:divider">@null</item>
<item name="android:dividerHeight">0dp</item> <item name="android:dividerHeight">0dp</item>
<item name="android:cacheColorHint">@android:color/transparent</item> <item name="android:cacheColorHint">@android:color/transparent</item>
<item name="android:layout_height">match_parent</item> <item name="android:layout_height">match_parent</item>
<item name="android:layout_width">match_parent</item> <item name="android:layout_width">match_parent</item>
<item name="android:layout_weight">1</item> <item name="android:layout_weight">1</item>
</style> </style>
<style name="default_fragment_title_style"> <style name="default_fragment_title_style">
<item name="android:textColor">@android:color/white</item> <item name="android:textColor">@android:color/white</item>
<item name="android:textSize">25sp</item> <item name="android:textSize">25sp</item>
<item name="android:layout_marginLeft">6dp</item> <item name="android:layout_marginLeft">6dp</item>
</style> </style>
<style name="default_button_style" parent="button_style"> <style name="default_button_style" parent="button_style">
<item name="android:background">@drawable/metro_button_blue</item> <item name="android:background">@drawable/metro_button_blue</item>
</style> </style>
<style name="default_fragment_layout_style"> <style name="default_fragment_layout_style">
<item name="android:layout_marginBottom">5dp</item> <item name="android:layout_marginBottom">5dp</item>
<item name="android:layout_marginTop">5dp</item> <item name="android:layout_marginTop">5dp</item>
<item name="android:layout_marginLeft">5dp</item> <item name="android:layout_marginLeft">5dp</item>
<item name="android:layout_marginRight">0dp</item> <item name="android:layout_marginRight">0dp</item>
</style> </style>
<style name="default_theme" parent="Theme.Sherlock"> <style name="default_theme" parent="Theme.Sherlock">
<item name="digitButtonStyle">@style/default_digit_button_style</item> <item name="digitButtonStyle">@style/default_digit_button_style</item>
<item name="controlButtonStyle">@style/default_control_button_style</item> <item name="controlButtonStyle">@style/default_control_button_style</item>
<item name="controlImageButtonStyle">@style/default_control_image_button_style</item> <item name="controlImageButtonStyle">@style/default_control_image_button_style</item>
<item name="operationButtonStyle">@style/default_operation_button_style</item> <item name="operationButtonStyle">@style/default_operation_button_style</item>
<item name="fragmentLayoutStyle">@style/default_fragment_layout_style</item> <item name="fragmentLayoutStyle">@style/default_fragment_layout_style</item>
<item name="secondPaneStyle">@style/default_second_pane_style</item> <item name="secondPaneStyle">@style/default_second_pane_style</item>
<item name="fragmentTitleStyle">@style/default_fragment_title_style</item> <item name="fragmentTitleStyle">@style/default_fragment_title_style</item>
<item name="fragmentListViewStyle">@style/default_fragment_list_view_style</item> <item name="fragmentListViewStyle">@style/default_fragment_list_view_style</item>
<item name="buttonStyle">@style/default_button_style</item> <item name="buttonStyle">@style/default_button_style</item>
</style> </style>
</resources> </resources>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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