2 * Copyright © 2021 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.text.Editable;
23 import android.text.TextUtils;
24 import android.text.TextWatcher;
25 import android.view.Gravity;
26 import android.view.View;
27 import android.view.ViewGroup;
28 import android.view.inputmethod.EditorInfo;
29 import android.widget.AutoCompleteTextView;
30 import android.widget.EditText;
31 import android.widget.FrameLayout;
32 import android.widget.TextView;
34 import androidx.annotation.ColorInt;
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.DimensionUtils;
51 import net.ktnx.mobileledger.utils.Logger;
52 import net.ktnx.mobileledger.utils.MLDB;
53 import net.ktnx.mobileledger.utils.Misc;
54 import net.ktnx.mobileledger.utils.SimpleDate;
56 import java.text.DecimalFormatSymbols;
57 import java.text.ParseException;
58 import java.util.Date;
59 import java.util.Locale;
61 import static net.ktnx.mobileledger.ui.activity.NewTransactionModel.ItemType;
63 class NewTransactionItemHolder extends RecyclerView.ViewHolder
64 implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback {
65 private final String decimalDot;
66 private final TextView tvCurrency;
67 private final Observer<Boolean> showCommentsObserver;
68 private final TextView tvTransactionComment;
69 private final TextView tvDate;
70 private final AutoCompleteTextView tvDescription;
71 private final TextView tvDummy;
72 private final AutoCompleteTextView tvAccount;
73 private final TextView tvComment;
74 private final EditText tvAmount;
75 private final ViewGroup lHead;
76 private final ViewGroup lAccount;
77 private final FrameLayout lPadding;
78 private final MobileLedgerProfile mProfile;
79 private final Observer<SimpleDate> dateObserver;
80 private final Observer<String> descriptionObserver;
81 private final Observer<String> transactionCommentObserver;
82 private final Observer<String> hintObserver;
83 private final Observer<Integer> focusedAccountObserver;
84 private final Observer<Integer> accountCountObserver;
85 private final Observer<Boolean> editableObserver;
86 private final Observer<Currency.Position> currencyPositionObserver;
87 private final Observer<Boolean> currencyGapObserver;
88 private final Observer<Locale> localeObserver;
89 private final Observer<Currency> currencyObserver;
90 private final Observer<Boolean> showCurrencyObserver;
91 private final Observer<String> commentObserver;
92 private final Observer<Boolean> amountValidityObserver;
93 private final View tvCurrencyButton;
94 private String decimalSeparator;
95 private NewTransactionModel.Item item;
97 private boolean inUpdate = false;
98 private boolean syncingData = false;
99 //TODO multiple amounts with different currencies per posting
100 NewTransactionItemHolder(@NonNull View itemView, NewTransactionItemsAdapter adapter) {
102 lAccount = itemView.findViewById(R.id.ntr_account);
103 tvAccount = lAccount.findViewById(R.id.account_row_acc_name);
104 tvComment = lAccount.findViewById(R.id.comment);
105 tvTransactionComment = itemView.findViewById(R.id.transaction_comment);
106 new TextViewClearHelper().attachToTextView((EditText) tvComment);
107 tvAmount = itemView.findViewById(R.id.account_row_acc_amounts);
108 tvCurrency = itemView.findViewById(R.id.currency);
109 tvCurrencyButton = lAccount.findViewById(R.id.currencyButton);
110 tvDate = itemView.findViewById(R.id.new_transaction_date);
111 tvDescription = itemView.findViewById(R.id.new_transaction_description);
112 tvDummy = itemView.findViewById(R.id.dummy_text);
113 lHead = itemView.findViewById(R.id.ntr_data);
114 lPadding = itemView.findViewById(R.id.ntr_padding);
115 final View commentLayout = itemView.findViewById(R.id.comment_layout);
116 final View transactionCommentLayout =
117 itemView.findViewById(R.id.transaction_comment_layout);
119 tvDescription.setNextFocusForwardId(View.NO_ID);
120 tvAccount.setNextFocusForwardId(View.NO_ID);
121 tvAmount.setNextFocusForwardId(View.NO_ID); // magic!
123 tvDate.setOnClickListener(v -> pickTransactionDate());
125 lAccount.findViewById(R.id.comment_button)
126 .setOnClickListener(v -> {
127 tvComment.setVisibility(View.VISIBLE);
128 tvComment.requestFocus();
131 transactionCommentLayout.findViewById(R.id.comment_button)
132 .setOnClickListener(v -> {
133 tvTransactionComment.setVisibility(View.VISIBLE);
134 tvTransactionComment.requestFocus();
137 mProfile = Data.getProfile();
139 View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
140 final int id = v.getId();
142 boolean wasSyncing = syncingData;
145 final int pos = getAdapterPosition();
146 adapter.updateFocusedItem(pos);
148 case R.id.account_row_acc_name:
149 adapter.noteFocusIsOnAccount(pos);
151 case R.id.account_row_acc_amounts:
152 adapter.noteFocusIsOnAmount(pos);
155 adapter.noteFocusIsOnComment(pos);
157 case R.id.transaction_comment:
158 adapter.noteFocusIsOnTransactionComment(pos);
160 case R.id.new_transaction_description:
161 adapter.noteFocusIsOnDescription(pos);
166 syncingData = wasSyncing;
170 if (id == R.id.comment) {
171 commentFocusChanged(tvComment, hasFocus);
173 else if (id == R.id.transaction_comment) {
174 commentFocusChanged(tvTransactionComment, hasFocus);
178 tvDescription.setOnFocusChangeListener(focusMonitor);
179 tvAccount.setOnFocusChangeListener(focusMonitor);
180 tvAmount.setOnFocusChangeListener(focusMonitor);
181 tvComment.setOnFocusChangeListener(focusMonitor);
182 tvTransactionComment.setOnFocusChangeListener(focusMonitor);
184 MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
185 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
186 MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
187 "name", true, this, mProfile);
189 decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
190 .getMonetaryDecimalSeparator());
191 localeObserver = locale -> decimalSeparator = String.valueOf(
192 DecimalFormatSymbols.getInstance(locale)
193 .getMonetaryDecimalSeparator());
197 final TextWatcher tw = new TextWatcher() {
199 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
203 public void onTextChanged(CharSequence s, int start, int before, int count) {
207 public void afterTextChanged(Editable s) {
208 // debug("input", "text changed");
212 Logger.debug("textWatcher", "calling syncData()");
214 Logger.debug("textWatcher",
215 "syncData() returned, checking if transaction is submittable");
216 adapter.checkTransactionSubmittable();
217 Logger.debug("textWatcher", "done");
220 final TextWatcher amountWatcher = new TextWatcher() {
222 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
224 String.format(Locale.US, "beforeTextChanged: start=%d, count=%d, after=%d",
225 start, count, after));
228 public void onTextChanged(CharSequence s, int start, int before, int count) {}
230 public void afterTextChanged(Editable s) {
233 adapter.checkTransactionSubmittable();
236 tvDescription.addTextChangedListener(tw);
237 tvTransactionComment.addTextChangedListener(tw);
238 tvAccount.addTextChangedListener(tw);
239 tvComment.addTextChangedListener(tw);
240 tvAmount.addTextChangedListener(amountWatcher);
242 tvCurrencyButton.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 dateObserver = date -> {
255 tvDate.setText(item.getFormattedDate());
261 descriptionObserver = description -> {
266 tvDescription.setText(description);
272 transactionCommentObserver = transactionComment -> {
273 final View focusedView = tvTransactionComment.findFocus();
274 tvTransactionComment.setTypeface(null,
275 (focusedView == tvTransactionComment) ? Typeface.NORMAL : Typeface.ITALIC);
276 tvTransactionComment.setVisibility(
277 ((focusedView != tvTransactionComment) && TextUtils.isEmpty(transactionComment))
278 ? View.INVISIBLE : View.VISIBLE);
281 hintObserver = hint -> {
287 tvAmount.setHint(R.string.zero_amount);
289 tvAmount.setHint(hint);
295 editableObserver = this::setEditable;
296 commentFocusChanged(tvTransactionComment, false);
297 commentFocusChanged(tvComment, false);
298 focusedAccountObserver = index -> {
299 if ((index == null) || !index.equals(getAdapterPosition()) || itemView.hasFocus())
302 switch (item.getType()) {
304 // bad idea - double pop-up, and not really necessary.
305 // the user can tap the input to get the calendar
306 //if (!tvDate.hasFocus()) tvDate.requestFocus();
307 switch (item.getFocusedElement()) {
308 case TransactionComment:
309 tvTransactionComment.setVisibility(View.VISIBLE);
310 tvTransactionComment.requestFocus();
313 boolean focused = tvDescription.requestFocus();
314 // tvDescription.dismissDropDown();
316 Misc.showSoftKeyboard(
317 (NewTransactionActivity) tvDescription.getContext());
322 switch (item.getFocusedElement()) {
324 tvAmount.requestFocus();
327 tvComment.setVisibility(View.VISIBLE);
328 tvComment.requestFocus();
331 boolean focused = tvAccount.requestFocus();
332 tvAccount.dismissDropDown();
334 Misc.showSoftKeyboard(
335 (NewTransactionActivity) tvAccount.getContext());
342 accountCountObserver = count -> {
343 final int adapterPosition = getAdapterPosition();
344 final int layoutPosition = getLayoutPosition();
345 Logger.debug("holder",
346 String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
347 adapterPosition, layoutPosition, item.getType()
349 .concat(item.getType() ==
350 ItemType.transactionRow
351 ? String.format(Locale.US,
357 ? String.format(Locale.US,
362 if (adapterPosition == count)
363 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
365 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
368 currencyObserver = currency -> {
369 setCurrency(currency);
370 adapter.checkTransactionSubmittable();
373 currencyGapObserver =
374 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
377 currencyPositionObserver =
378 position -> updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
380 showCurrencyObserver = showCurrency -> {
382 tvCurrency.setVisibility(View.VISIBLE);
383 tvCurrencyButton.setVisibility(View.VISIBLE);
384 String defaultCommodity = mProfile.getDefaultCommodity();
386 (defaultCommodity == null) ? null : Currency.loadByName(defaultCommodity));
389 tvCurrency.setVisibility(View.GONE);
390 tvCurrencyButton.setVisibility(View.GONE);
391 item.setCurrency(null);
395 commentObserver = comment -> {
396 final View focusedView = tvComment.findFocus();
397 tvComment.setTypeface(null,
398 (focusedView == tvComment) ? Typeface.NORMAL : Typeface.ITALIC);
399 tvComment.setVisibility(
400 ((focusedView != tvComment) && TextUtils.isEmpty(comment)) ? View.INVISIBLE
404 showCommentsObserver = show -> {
405 final View amountLayout = itemView.findViewById(R.id.amount_layout);
406 ConstraintLayout.LayoutParams amountLayoutParams =
407 (ConstraintLayout.LayoutParams) amountLayout.getLayoutParams();
408 ConstraintLayout.LayoutParams accountParams =
409 (ConstraintLayout.LayoutParams) tvAccount.getLayoutParams();
411 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
412 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
414 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
415 amountLayoutParams.topToBottom = tvAccount.getId();
417 commentLayout.setVisibility(View.VISIBLE);
420 accountParams.endToStart = amountLayout.getId();
421 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
423 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
424 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
426 commentLayout.setVisibility(View.GONE);
429 tvAccount.setLayoutParams(accountParams);
430 amountLayout.setLayoutParams(amountLayoutParams);
432 transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
435 amountValidityObserver = valid -> {
436 tvAmount.setCompoundDrawablesRelativeWithIntrinsicBounds(
437 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
438 tvAmount.setMinEms(valid ? 4 : 5);
441 private void commentFocusChanged(TextView textView, boolean hasFocus) {
442 @ColorInt int textColor;
443 textColor = tvDummy.getTextColors()
446 textView.setTypeface(null, Typeface.NORMAL);
447 textView.setHint(R.string.transaction_account_comment_hint);
450 int alpha = (textColor >> 24 & 0xff);
451 alpha = 3 * alpha / 4;
452 textColor = (alpha << 24) | (0x00ffffff & textColor);
453 textView.setTypeface(null, Typeface.ITALIC);
454 textView.setHint("");
455 if (TextUtils.isEmpty(textView.getText())) {
456 textView.setVisibility(View.INVISIBLE);
459 textView.setTextColor(textColor);
462 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
463 ConstraintLayout.LayoutParams amountLP =
464 (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
465 ConstraintLayout.LayoutParams currencyLP =
466 (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
468 if (position == Currency.Position.before) {
469 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
470 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
472 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
473 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
474 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
475 amountLP.startToEnd = tvCurrency.getId();
477 tvCurrency.setGravity(Gravity.END);
480 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
481 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
483 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
484 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
485 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
486 amountLP.endToStart = tvCurrency.getId();
488 tvCurrency.setGravity(Gravity.START);
491 amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
492 currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
494 tvAmount.setLayoutParams(amountLP);
495 tvCurrency.setLayoutParams(currencyLP);
497 // distance between the amount and the currency symbol
498 int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
500 if (position == Currency.Position.before) {
501 tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
504 tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
507 private void setCurrencyString(String currency) {
508 @ColorInt int textColor = tvDummy.getTextColors()
510 if ((currency == null) || currency.isEmpty()) {
511 tvCurrency.setText(R.string.currency_symbol);
512 int alpha = (textColor >> 24) & 0xff;
513 alpha = alpha * 3 / 4;
514 tvCurrency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
517 tvCurrency.setText(currency);
518 tvCurrency.setTextColor(textColor);
521 private void setCurrency(Currency currency) {
522 setCurrencyString((currency == null) ? null : currency.getName());
524 private void setEditable(Boolean editable) {
525 tvDate.setEnabled(editable);
526 tvDescription.setEnabled(editable);
527 tvAccount.setEnabled(editable);
528 tvAmount.setEnabled(editable);
530 private void beginUpdates() {
532 throw new RuntimeException("Already in update mode");
535 private void endUpdates() {
537 throw new RuntimeException("Not in update mode");
543 * Stores the data from the UI elements into the model item
544 * Returns true if there were changes made that suggest transaction has to be
545 * checked for being submittable
547 private boolean syncData() {
552 Logger.debug("new-trans", "skipping syncData() loop");
559 switch (item.getType()) {
561 item.setDate(String.valueOf(tvDate.getText()));
562 item.setDescription(String.valueOf(tvDescription.getText()));
563 item.setTransactionComment(String.valueOf(tvTransactionComment.getText()));
566 final LedgerTransactionAccount account = item.getAccount();
567 account.setAccountName(String.valueOf(tvAccount.getText()));
569 item.setComment(String.valueOf(tvComment.getText()));
571 String amount = String.valueOf(tvAmount.getText());
572 amount = amount.trim();
574 if (amount.isEmpty()) {
575 account.resetAmount();
576 item.validateAmount();
580 amount = amount.replace(decimalSeparator, decimalDot);
581 account.setAmount(Float.parseFloat(amount));
582 item.validateAmount();
584 catch (NumberFormatException e) {
585 Logger.debug("new-trans", String.format(
586 "assuming amount is not set due to number format exception. " +
587 "input was '%s'", amount));
588 account.invalidateAmount();
589 item.invalidateAmount();
591 final String curr = String.valueOf(tvCurrency.getText());
592 if (curr.equals(tvCurrency.getContext()
594 .getString(R.string.currency_symbol)) ||
596 account.setCurrency(null);
598 account.setCurrency(curr);
603 throw new RuntimeException("Should not happen");
608 catch (ParseException e) {
609 throw new RuntimeException("Should not happen", e);
615 private void pickTransactionDate() {
616 DatePickerFragment picker = new DatePickerFragment();
617 picker.setFutureDates(mProfile.getFutureDates());
618 picker.setOnDatePickedListener(this);
619 picker.setCurrentDateFromText(tvDate.getText());
620 picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
626 * @param item updates the UI elements with the data from the model item
628 @SuppressLint("DefaultLocale")
629 public void setData(NewTransactionModel.Item item) {
632 if (this.item != null && !this.item.equals(item)) {
633 this.item.stopObservingDate(dateObserver);
634 this.item.stopObservingDescription(descriptionObserver);
635 this.item.stopObservingTransactionComment(transactionCommentObserver);
636 this.item.stopObservingAmountHint(hintObserver);
637 this.item.stopObservingEditableFlag(editableObserver);
639 .stopObservingFocusedItem(focusedAccountObserver);
641 .stopObservingAccountCount(accountCountObserver);
642 Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
643 Data.currencyGap.removeObserver(currencyGapObserver);
644 Data.locale.removeObserver(localeObserver);
645 this.item.stopObservingCurrency(currencyObserver);
646 this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
647 this.item.stopObservingComment(commentObserver);
648 this.item.getModel().showComments.removeObserver(showCommentsObserver);
649 this.item.stopObservingAmountValidity(amountValidityObserver);
654 switch (item.getType()) {
656 tvDate.setText(item.getFormattedDate());
657 tvDescription.setText(item.getDescription());
658 tvTransactionComment.setText(item.getTransactionComment());
659 lHead.setVisibility(View.VISIBLE);
660 lAccount.setVisibility(View.GONE);
661 lPadding.setVisibility(View.GONE);
665 LedgerTransactionAccount acc = item.getAccount();
666 tvAccount.setText(acc.getAccountName());
667 tvComment.setText(acc.getComment());
668 if (acc.isAmountSet()) {
669 tvAmount.setText(String.format("%1.2f", acc.getAmount()));
672 tvAmount.setText("");
673 // tvAmount.setHint(R.string.zero_amount);
675 tvAmount.setHint(item.getAmountHint());
676 setCurrencyString(acc.getCurrency());
677 lHead.setVisibility(View.GONE);
678 lAccount.setVisibility(View.VISIBLE);
679 lPadding.setVisibility(View.GONE);
683 lHead.setVisibility(View.GONE);
684 lAccount.setVisibility(View.GONE);
685 lPadding.setVisibility(View.VISIBLE);
689 if (this.item == null) { // was null or has changed
691 final NewTransactionActivity activity =
692 (NewTransactionActivity) tvDescription.getContext();
694 if (!item.isBottomFiller()) {
695 item.observeEditableFlag(activity, editableObserver);
697 .observeFocusedItem(activity, focusedAccountObserver);
699 .observeShowComments(activity, showCommentsObserver);
701 switch (item.getType()) {
703 item.observeDate(activity, dateObserver);
704 item.observeDescription(activity, descriptionObserver);
705 item.observeTransactionComment(activity, transactionCommentObserver);
708 item.observeAmountHint(activity, hintObserver);
709 Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
710 Data.currencyGap.observe(activity, currencyGapObserver);
711 Data.locale.observe(activity, localeObserver);
712 item.observeCurrency(activity, currencyObserver);
713 item.getModel().showCurrency.observe(activity, showCurrencyObserver);
714 item.observeComment(activity, commentObserver);
716 .observeAccountCount(activity, accountCountObserver);
717 item.observeAmountValidity(activity, amountValidityObserver);
727 public void onDatePicked(int year, int month, int day) {
728 item.setDate(new SimpleDate(year, month + 1, day));
729 boolean focused = tvDescription.requestFocus();
731 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
735 public void descriptionSelected(String description) {
736 tvAccount.setText(description);
737 tvAmount.requestFocus(View.FOCUS_FORWARD);