2 * Copyright © 2019 Damyan Ivanov.
3 * This file is part of MoLe.
4 * MoLe is free software: you can distribute it and/or modify it
5 * under the term of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your opinion), any later version.
9 * MoLe is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License terms for details.
14 * You should have received a copy of the GNU General Public License
15 * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
18 package net.ktnx.mobileledger.ui.activity;
20 import android.annotation.SuppressLint;
21 import android.graphics.Typeface;
22 import android.os.Build;
23 import android.text.Editable;
24 import android.text.TextWatcher;
25 import android.text.method.DigitsKeyListener;
26 import android.view.Gravity;
27 import android.view.View;
28 import android.view.ViewGroup;
29 import android.view.inputmethod.EditorInfo;
30 import android.widget.AutoCompleteTextView;
31 import android.widget.EditText;
32 import android.widget.FrameLayout;
33 import android.widget.TextView;
35 import androidx.annotation.NonNull;
36 import androidx.appcompat.app.AppCompatActivity;
37 import androidx.constraintlayout.widget.ConstraintLayout;
38 import androidx.lifecycle.Observer;
39 import androidx.recyclerview.widget.RecyclerView;
41 import net.ktnx.mobileledger.R;
42 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
43 import net.ktnx.mobileledger.model.Currency;
44 import net.ktnx.mobileledger.model.Data;
45 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
46 import net.ktnx.mobileledger.model.MobileLedgerProfile;
47 import net.ktnx.mobileledger.ui.CurrencySelectorFragment;
48 import net.ktnx.mobileledger.ui.DatePickerFragment;
49 import net.ktnx.mobileledger.ui.TextViewClearHelper;
50 import net.ktnx.mobileledger.utils.Colors;
51 import net.ktnx.mobileledger.utils.DimensionUtils;
52 import net.ktnx.mobileledger.utils.Logger;
53 import net.ktnx.mobileledger.utils.MLDB;
54 import net.ktnx.mobileledger.utils.Misc;
56 import java.text.DecimalFormatSymbols;
57 import java.util.Calendar;
58 import java.util.Date;
59 import java.util.GregorianCalendar;
60 import java.util.Locale;
62 import static net.ktnx.mobileledger.ui.activity.NewTransactionModel.ItemType;
64 class NewTransactionItemHolder extends RecyclerView.ViewHolder
65 implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback {
66 private final String decimalSeparator;
67 private final String decimalDot;
68 private final TextView tvCurrency;
69 private final Observer<Boolean> showCommentsObserver;
70 private final TextView tvTransactionComment;
71 private NewTransactionModel.Item item;
72 private TextView tvDate;
73 private AutoCompleteTextView tvDescription;
74 private AutoCompleteTextView tvAccount;
75 private TextView tvComment;
76 private EditText tvAmount;
77 private ViewGroup lHead;
78 private ViewGroup lAccount;
79 private FrameLayout lPadding;
80 private MobileLedgerProfile mProfile;
82 private Observer<Date> dateObserver;
83 private Observer<String> descriptionObserver;
84 private Observer<String> hintObserver;
85 private Observer<Integer> focusedAccountObserver;
86 private Observer<Integer> accountCountObserver;
87 private Observer<Boolean> editableObserver;
88 private Observer<Currency.Position> currencyPositionObserver;
89 private Observer<Boolean> currencyGapObserver;
90 private Observer<Locale> localeObserver;
91 private Observer<Currency> currencyObserver;
92 private Observer<Boolean> showCurrencyObserver;
93 private Observer<String> commentObserver;
94 private boolean inUpdate = false;
95 private boolean syncingData = false;
96 private View commentButton;
97 //TODO multiple amounts with different currencies per posting
98 NewTransactionItemHolder(@NonNull View itemView, NewTransactionItemsAdapter adapter) {
100 lAccount = itemView.findViewById(R.id.ntr_account);
101 tvAccount = lAccount.findViewById(R.id.account_row_acc_name);
102 tvComment = lAccount.findViewById(R.id.comment);
103 tvTransactionComment = itemView.findViewById(R.id.transaction_comment);
104 new TextViewClearHelper().attachToTextView((EditText) tvComment);
105 commentButton = lAccount.findViewById(R.id.comment_button);
106 tvAmount = itemView.findViewById(R.id.account_row_acc_amounts);
107 tvCurrency = itemView.findViewById(R.id.currency);
108 tvDate = itemView.findViewById(R.id.new_transaction_date);
109 tvDescription = itemView.findViewById(R.id.new_transaction_description);
110 lHead = itemView.findViewById(R.id.ntr_data);
111 lPadding = itemView.findViewById(R.id.ntr_padding);
112 final View commentLayout = itemView.findViewById(R.id.comment_layout);
113 final View transactionCommentLayout =
114 itemView.findViewById(R.id.transaction_comment_layout);
116 tvDescription.setNextFocusForwardId(View.NO_ID);
117 tvAccount.setNextFocusForwardId(View.NO_ID);
118 tvAmount.setNextFocusForwardId(View.NO_ID); // magic!
120 tvDate.setOnClickListener(v -> pickTransactionDate());
122 commentButton.setOnClickListener(v -> {
123 tvComment.setVisibility(View.VISIBLE);
124 tvComment.requestFocus();
127 transactionCommentLayout.findViewById(R.id.comment_button)
128 .setOnClickListener(v -> {
129 tvTransactionComment.setVisibility(View.VISIBLE);
130 tvTransactionComment.requestFocus();
133 mProfile = Data.profile.getValue();
134 if (mProfile == null)
135 throw new AssertionError();
137 View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
138 final int id = v.getId();
140 boolean wasSyncing = syncingData;
143 final int pos = getAdapterPosition();
144 adapter.updateFocusedItem(pos);
146 case R.id.account_row_acc_name:
147 adapter.noteFocusIsOnAccount(pos);
149 case R.id.account_row_acc_amounts:
150 adapter.noteFocusIsOnAmount(pos);
153 adapter.noteFocusIsOnComment(pos);
158 syncingData = wasSyncing;
162 if (id == R.id.comment) {
163 commentFocusChanged(commentLayout, tvComment, hasFocus);
165 else if ( id == R.id.transaction_comment) {
166 commentFocusChanged(transactionCommentLayout, tvTransactionComment, hasFocus);
170 tvDescription.setOnFocusChangeListener(focusMonitor);
171 tvAccount.setOnFocusChangeListener(focusMonitor);
172 tvAmount.setOnFocusChangeListener(focusMonitor);
173 tvComment.setOnFocusChangeListener(focusMonitor);
175 MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
176 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
177 MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
178 "name", true, this, mProfile);
180 // FIXME: react on configuration (locale) changes
181 decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
182 .getMonetaryDecimalSeparator());
185 final TextWatcher tw = new TextWatcher() {
187 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
191 public void onTextChanged(CharSequence s, int start, int before, int count) {
195 public void afterTextChanged(Editable s) {
196 // debug("input", "text changed");
200 Logger.debug("textWatcher", "calling syncData()");
202 Logger.debug("textWatcher",
203 "syncData() returned, checking if transaction is submittable");
204 adapter.checkTransactionSubmittable();
205 Logger.debug("textWatcher", "done");
208 final TextWatcher amountWatcher = new TextWatcher() {
210 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
212 String.format(Locale.US, "beforeTextChanged: start=%d, count=%d, after=%d",
213 start, count, after));
216 public void onTextChanged(CharSequence s, int start, int before, int count) {}
218 public void afterTextChanged(Editable s) {
219 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
220 // only one decimal separator is allowed
221 // plus and minus are allowed only at the beginning
222 String allowed = "0123456789";
223 String val = s.toString();
224 Logger.debug("input", val);
225 if (val.isEmpty() || (tvAmount.getSelectionStart() == 0))
227 if (!val.contains(decimalSeparator) && !val.contains(decimalDot))
228 allowed += decimalSeparator + decimalDot;
230 tvAmount.setKeyListener(DigitsKeyListener.getInstance(allowed));
234 adapter.checkTransactionSubmittable();
237 tvDescription.addTextChangedListener(tw);
238 tvAccount.addTextChangedListener(tw);
239 tvComment.addTextChangedListener(tw);
240 tvAmount.addTextChangedListener(amountWatcher);
242 tvCurrency.setOnClickListener(v -> {
243 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
244 cpf.showPositionAndPadding();
245 cpf.setOnCurrencySelectedListener(c -> item.setCurrency(c));
246 final AppCompatActivity activity = (AppCompatActivity) v.getContext();
247 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
250 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
251 tvAmount.setKeyListener(
252 DigitsKeyListener.getInstance(Data.locale.getValue(), true, true));
254 tvAmount.setKeyListener(
255 DigitsKeyListener.getInstance("0123456789+-" + decimalSeparator + decimalDot));
257 dateObserver = date -> {
262 tvDate.setText(item.getFormattedDate());
268 descriptionObserver = description -> {
273 tvDescription.setText(description);
279 hintObserver = hint -> {
285 tvAmount.setHint(R.string.zero_amount);
287 tvAmount.setHint(hint);
293 editableObserver = this::setEditable;
294 focusedAccountObserver = index -> {
295 if ((index != null) && index.equals(getAdapterPosition())) {
296 switch (item.getType()) {
298 // bad idea - double pop-up, and not really necessary.
299 // the user can tap the input to get the calendar
300 //if (!tvDate.hasFocus()) tvDate.requestFocus();
301 boolean focused = tvDescription.requestFocus();
302 tvDescription.dismissDropDown();
304 Misc.showSoftKeyboard(
305 (NewTransactionActivity) tvDescription.getContext());
308 // do nothing if a row element already has the focus
309 if (!itemView.hasFocus()) {
310 switch (item.getFocusedElement()) {
312 tvAmount.requestFocus();
315 tvComment.setVisibility(View.VISIBLE);
316 tvComment.requestFocus();
319 focused = tvAccount.requestFocus();
320 tvAccount.dismissDropDown();
322 Misc.showSoftKeyboard(
323 (NewTransactionActivity) tvAccount.getContext());
332 accountCountObserver = count -> {
333 final int adapterPosition = getAdapterPosition();
334 final int layoutPosition = getLayoutPosition();
335 Logger.debug("holder",
336 String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
337 adapterPosition, layoutPosition, item.getType()
339 .concat(item.getType() ==
340 ItemType.transactionRow
341 ? String.format(Locale.US,
347 ? String.format(Locale.US,
352 if (adapterPosition == count)
353 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
355 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
358 localeObserver = locale -> {
359 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
360 tvAmount.setKeyListener(DigitsKeyListener.getInstance(locale, true, true));
363 currencyObserver = currency -> {
364 setCurrency(currency);
365 adapter.checkTransactionSubmittable();
368 currencyGapObserver =
369 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
372 currencyPositionObserver =
373 position -> updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
375 showCurrencyObserver = showCurrency -> {
377 tvCurrency.setVisibility(View.VISIBLE);
380 tvCurrency.setVisibility(View.GONE);
381 item.setCurrency(null);
385 commentObserver = comment -> {
386 final View focusedView = tvComment.findFocus();
387 tvComment.setTypeface(null,
388 (focusedView == tvComment) ? Typeface.NORMAL : Typeface.ITALIC);
389 tvComment.setVisibility(
390 ((focusedView != tvComment) && Misc.isEmptyOrNull(comment)) ? View.INVISIBLE
394 showCommentsObserver = show -> {
395 final View amountLayout = itemView.findViewById(R.id.amount_layout);
396 ConstraintLayout.LayoutParams amountLayoutParams =
397 (ConstraintLayout.LayoutParams) amountLayout.getLayoutParams();
398 ConstraintLayout.LayoutParams accountParams =
399 (ConstraintLayout.LayoutParams) tvAccount.getLayoutParams();
401 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
402 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
404 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
405 amountLayoutParams.topToBottom = tvAccount.getId();
407 commentLayout.setVisibility(View.VISIBLE);
410 accountParams.endToStart = amountLayout.getId();
411 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
413 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
414 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
416 commentLayout.setVisibility(View.GONE);
419 tvAccount.setLayoutParams(accountParams);
420 amountLayout.setLayoutParams(amountLayoutParams);
422 transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
425 private void commentFocusChanged(View layout, TextView textView, boolean hasFocus) {
428 textColor = Colors.defaultTextColor;
429 textView.setTypeface(null, Typeface.NORMAL);
430 textView.setHint(R.string.transaction_account_comment_hint);
433 textColor = Colors.defaultTextColorDisabled;
434 textView.setTypeface(null, Typeface.ITALIC);
435 textView.setHint("");
436 if (Misc.isEmptyOrNull(textView.getText())) {
437 textView.setVisibility(View.INVISIBLE);
440 textView.setTextColor(textColor);
443 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
444 ConstraintLayout.LayoutParams amountLP =
445 (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
446 ConstraintLayout.LayoutParams currencyLP =
447 (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
449 if (position == Currency.Position.before) {
450 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
451 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
453 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
454 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
455 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
456 amountLP.startToEnd = tvCurrency.getId();
458 tvCurrency.setGravity(Gravity.END);
461 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
462 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
464 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
465 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
466 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
467 amountLP.endToStart = tvCurrency.getId();
469 tvCurrency.setGravity(Gravity.START);
472 amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
473 currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
475 tvAmount.setLayoutParams(amountLP);
476 tvCurrency.setLayoutParams(currencyLP);
478 // distance between the amount and the currency symbol
479 int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
481 if (position == Currency.Position.before) {
482 tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
485 tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
488 private void setCurrencyString(String currency) {
489 if ((currency == null) || currency.isEmpty()) {
490 tvCurrency.setText(R.string.currency_symbol);
491 tvCurrency.setTextColor(0x7f000000 + (0x00ffffff & Colors.defaultTextColor));
494 tvCurrency.setText(currency);
495 tvCurrency.setTextColor(Colors.defaultTextColor);
498 private void setCurrency(Currency currency) {
499 setCurrencyString((currency == null) ? null : currency.getName());
501 private void setEditable(Boolean editable) {
502 tvDate.setEnabled(editable);
503 tvDescription.setEnabled(editable);
504 tvAccount.setEnabled(editable);
505 tvAmount.setEnabled(editable);
507 private void beginUpdates() {
509 throw new RuntimeException("Already in update mode");
512 private void endUpdates() {
514 throw new RuntimeException("Not in update mode");
520 * Stores the data from the UI elements into the model item
521 * Returns true if there were changes made that suggest transaction has to be
522 * checked for being submittable
524 private boolean syncData() {
529 Logger.debug("new-trans", "skipping syncData() loop");
536 switch (item.getType()) {
538 item.setDate(String.valueOf(tvDate.getText()));
539 item.setDescription(String.valueOf(tvDescription.getText()));
542 final LedgerTransactionAccount account = item.getAccount();
543 account.setAccountName(String.valueOf(tvAccount.getText()));
545 item.setComment(String.valueOf(tvComment.getText()));
547 String amount = String.valueOf(tvAmount.getText());
548 amount = amount.trim();
550 if (amount.isEmpty()) {
551 account.resetAmount();
552 // account.setCurrency(null);
556 amount = amount.replace(decimalSeparator, decimalDot);
557 account.setAmount(Float.parseFloat(amount));
559 catch (NumberFormatException e) {
560 Logger.debug("new-trans", String.format(
561 "assuming amount is not set due to number format exception. " +
562 "input was '%s'", amount));
563 account.resetAmount();
565 final String curr = String.valueOf(tvCurrency.getText());
566 if (curr.equals(tvCurrency.getContext()
568 .getString(R.string.currency_symbol)) ||
570 account.setCurrency(null);
572 account.setCurrency(curr);
577 throw new RuntimeException("Should not happen");
586 private void pickTransactionDate() {
587 DatePickerFragment picker = new DatePickerFragment();
588 picker.setFutureDates(mProfile.getFutureDates());
589 picker.setOnDatePickedListener(this);
590 picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
596 * @param item updates the UI elements with the data from the model item
598 @SuppressLint("DefaultLocale")
599 public void setData(NewTransactionModel.Item item) {
602 if (this.item != null && !this.item.equals(item)) {
603 this.item.stopObservingDate(dateObserver);
604 this.item.stopObservingDescription(descriptionObserver);
605 this.item.stopObservingAmountHint(hintObserver);
606 this.item.stopObservingEditableFlag(editableObserver);
608 .stopObservingFocusedItem(focusedAccountObserver);
610 .stopObservingAccountCount(accountCountObserver);
611 Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
612 Data.currencyGap.removeObserver(currencyGapObserver);
613 Data.locale.removeObserver(localeObserver);
614 this.item.stopObservingCurrency(currencyObserver);
615 this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
616 this.item.stopObservingComment(commentObserver);
617 this.item.getModel().showComments.removeObserver(showCommentsObserver);
622 switch (item.getType()) {
624 tvDate.setText(item.getFormattedDate());
625 tvDescription.setText(item.getDescription());
626 lHead.setVisibility(View.VISIBLE);
627 lAccount.setVisibility(View.GONE);
628 lPadding.setVisibility(View.GONE);
632 LedgerTransactionAccount acc = item.getAccount();
633 tvAccount.setText(acc.getAccountName());
634 tvComment.setText(acc.getComment());
635 if (acc.isAmountSet()) {
636 tvAmount.setText(String.format("%1.2f", acc.getAmount()));
639 tvAmount.setText("");
640 // tvAmount.setHint(R.string.zero_amount);
642 tvAmount.setHint(item.getAmountHint());
643 setCurrencyString(acc.getCurrency());
644 lHead.setVisibility(View.GONE);
645 lAccount.setVisibility(View.VISIBLE);
646 lPadding.setVisibility(View.GONE);
650 lHead.setVisibility(View.GONE);
651 lAccount.setVisibility(View.GONE);
652 lPadding.setVisibility(View.VISIBLE);
656 if (this.item == null) { // was null or has changed
658 final NewTransactionActivity activity =
659 (NewTransactionActivity) tvDescription.getContext();
661 if (!item.isOfType(ItemType.bottomFiller)) {
662 item.observeEditableFlag(activity, editableObserver);
664 .observeFocusedItem(activity, focusedAccountObserver);
666 .observeShowComments(activity, showCommentsObserver);
668 switch (item.getType()) {
670 item.observeDate(activity, dateObserver);
671 item.observeDescription(activity, descriptionObserver);
674 item.observeAmountHint(activity, hintObserver);
675 Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
676 Data.currencyGap.observe(activity, currencyGapObserver);
677 Data.locale.observe(activity, localeObserver);
678 item.observeCurrency(activity, currencyObserver);
679 item.getModel().showCurrency.observe(activity, showCurrencyObserver);
680 item.observeComment(activity, commentObserver);
682 .observeAccountCount(activity, accountCountObserver);
692 public void onDatePicked(int year, int month, int day) {
693 final Calendar c = GregorianCalendar.getInstance();
694 c.set(year, month, day);
695 item.setDate(c.getTime());
696 boolean focused = tvDescription.requestFocus();
698 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
702 public void descriptionSelected(String description) {
703 tvAccount.setText(description);
704 tvAmount.requestFocus(View.FOCUS_FORWARD);