2 * Copyright © 2020 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 String decimalSeparator;
94 private NewTransactionModel.Item item;
96 private boolean inUpdate = false;
97 private boolean syncingData = false;
98 //TODO multiple amounts with different currencies per posting
99 NewTransactionItemHolder(@NonNull View itemView, NewTransactionItemsAdapter adapter) {
101 lAccount = itemView.findViewById(R.id.ntr_account);
102 tvAccount = lAccount.findViewById(R.id.account_row_acc_name);
103 tvComment = lAccount.findViewById(R.id.comment);
104 tvTransactionComment = itemView.findViewById(R.id.transaction_comment);
105 new TextViewClearHelper().attachToTextView((EditText) tvComment);
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 tvDummy = itemView.findViewById(R.id.dummy_text);
111 lHead = itemView.findViewById(R.id.ntr_data);
112 lPadding = itemView.findViewById(R.id.ntr_padding);
113 final View commentLayout = itemView.findViewById(R.id.comment_layout);
114 final View transactionCommentLayout =
115 itemView.findViewById(R.id.transaction_comment_layout);
117 tvDescription.setNextFocusForwardId(View.NO_ID);
118 tvAccount.setNextFocusForwardId(View.NO_ID);
119 tvAmount.setNextFocusForwardId(View.NO_ID); // magic!
121 tvDate.setOnClickListener(v -> pickTransactionDate());
123 lAccount.findViewById(R.id.comment_button)
124 .setOnClickListener(v -> {
125 tvComment.setVisibility(View.VISIBLE);
126 tvComment.requestFocus();
129 transactionCommentLayout.findViewById(R.id.comment_button)
130 .setOnClickListener(v -> {
131 tvTransactionComment.setVisibility(View.VISIBLE);
132 tvTransactionComment.requestFocus();
135 mProfile = Data.getProfile();
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);
155 case R.id.transaction_comment:
156 adapter.noteFocusIsOnTransactionComment(pos);
158 case R.id.new_transaction_description:
159 adapter.noteFocusIsOnDescription(pos);
164 syncingData = wasSyncing;
168 if (id == R.id.comment) {
169 commentFocusChanged(tvComment, hasFocus);
171 else if (id == R.id.transaction_comment) {
172 commentFocusChanged(tvTransactionComment, hasFocus);
176 tvDescription.setOnFocusChangeListener(focusMonitor);
177 tvAccount.setOnFocusChangeListener(focusMonitor);
178 tvAmount.setOnFocusChangeListener(focusMonitor);
179 tvComment.setOnFocusChangeListener(focusMonitor);
180 tvTransactionComment.setOnFocusChangeListener(focusMonitor);
182 MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
183 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
184 MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
185 "name", true, this, mProfile);
187 decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
188 .getMonetaryDecimalSeparator());
189 localeObserver = locale -> decimalSeparator = String.valueOf(
190 DecimalFormatSymbols.getInstance(locale)
191 .getMonetaryDecimalSeparator());
195 final TextWatcher tw = new TextWatcher() {
197 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
201 public void onTextChanged(CharSequence s, int start, int before, int count) {
205 public void afterTextChanged(Editable s) {
206 // debug("input", "text changed");
210 Logger.debug("textWatcher", "calling syncData()");
212 Logger.debug("textWatcher",
213 "syncData() returned, checking if transaction is submittable");
214 adapter.checkTransactionSubmittable();
215 Logger.debug("textWatcher", "done");
218 final TextWatcher amountWatcher = new TextWatcher() {
220 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
222 String.format(Locale.US, "beforeTextChanged: start=%d, count=%d, after=%d",
223 start, count, after));
226 public void onTextChanged(CharSequence s, int start, int before, int count) {}
228 public void afterTextChanged(Editable s) {
231 adapter.checkTransactionSubmittable();
234 tvDescription.addTextChangedListener(tw);
235 tvTransactionComment.addTextChangedListener(tw);
236 tvAccount.addTextChangedListener(tw);
237 tvComment.addTextChangedListener(tw);
238 tvAmount.addTextChangedListener(amountWatcher);
240 tvCurrency.setOnClickListener(v -> {
241 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
242 cpf.showPositionAndPadding();
243 cpf.setOnCurrencySelectedListener(c -> item.setCurrency(c));
244 final AppCompatActivity activity = (AppCompatActivity) v.getContext();
245 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
248 dateObserver = date -> {
253 tvDate.setText(item.getFormattedDate());
259 descriptionObserver = description -> {
264 tvDescription.setText(description);
270 transactionCommentObserver = transactionComment -> {
271 final View focusedView = tvTransactionComment.findFocus();
272 tvTransactionComment.setTypeface(null,
273 (focusedView == tvTransactionComment) ? Typeface.NORMAL : Typeface.ITALIC);
274 tvTransactionComment.setVisibility(
275 ((focusedView != tvTransactionComment) && TextUtils.isEmpty(transactionComment))
276 ? View.INVISIBLE : View.VISIBLE);
279 hintObserver = hint -> {
285 tvAmount.setHint(R.string.zero_amount);
287 tvAmount.setHint(hint);
293 editableObserver = this::setEditable;
294 commentFocusChanged(tvTransactionComment, false);
295 commentFocusChanged(tvComment, false);
296 focusedAccountObserver = index -> {
297 if ((index == null) || !index.equals(getAdapterPosition()) || itemView.hasFocus())
300 switch (item.getType()) {
302 // bad idea - double pop-up, and not really necessary.
303 // the user can tap the input to get the calendar
304 //if (!tvDate.hasFocus()) tvDate.requestFocus();
305 switch (item.getFocusedElement()) {
306 case TransactionComment:
307 tvTransactionComment.setVisibility(View.VISIBLE);
308 tvTransactionComment.requestFocus();
311 boolean focused = tvDescription.requestFocus();
312 tvDescription.dismissDropDown();
314 Misc.showSoftKeyboard(
315 (NewTransactionActivity) tvDescription.getContext());
320 switch (item.getFocusedElement()) {
322 tvAmount.requestFocus();
325 tvComment.setVisibility(View.VISIBLE);
326 tvComment.requestFocus();
329 boolean focused = tvAccount.requestFocus();
330 tvAccount.dismissDropDown();
332 Misc.showSoftKeyboard(
333 (NewTransactionActivity) tvAccount.getContext());
340 accountCountObserver = count -> {
341 final int adapterPosition = getAdapterPosition();
342 final int layoutPosition = getLayoutPosition();
343 Logger.debug("holder",
344 String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
345 adapterPosition, layoutPosition, item.getType()
347 .concat(item.getType() ==
348 ItemType.transactionRow
349 ? String.format(Locale.US,
355 ? String.format(Locale.US,
360 if (adapterPosition == count)
361 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
363 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
366 currencyObserver = currency -> {
367 setCurrency(currency);
368 adapter.checkTransactionSubmittable();
371 currencyGapObserver =
372 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
375 currencyPositionObserver =
376 position -> updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
378 showCurrencyObserver = showCurrency -> {
380 tvCurrency.setVisibility(View.VISIBLE);
381 String defaultCommodity = mProfile.getDefaultCommodity();
383 (defaultCommodity == null) ? null : Currency.loadByName(defaultCommodity));
386 tvCurrency.setVisibility(View.GONE);
387 item.setCurrency(null);
391 commentObserver = comment -> {
392 final View focusedView = tvComment.findFocus();
393 tvComment.setTypeface(null,
394 (focusedView == tvComment) ? Typeface.NORMAL : Typeface.ITALIC);
395 tvComment.setVisibility(
396 ((focusedView != tvComment) && TextUtils.isEmpty(comment)) ? View.INVISIBLE
400 showCommentsObserver = show -> {
401 final View amountLayout = itemView.findViewById(R.id.amount_layout);
402 ConstraintLayout.LayoutParams amountLayoutParams =
403 (ConstraintLayout.LayoutParams) amountLayout.getLayoutParams();
404 ConstraintLayout.LayoutParams accountParams =
405 (ConstraintLayout.LayoutParams) tvAccount.getLayoutParams();
407 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
408 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
410 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
411 amountLayoutParams.topToBottom = tvAccount.getId();
413 commentLayout.setVisibility(View.VISIBLE);
416 accountParams.endToStart = amountLayout.getId();
417 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
419 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
420 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
422 commentLayout.setVisibility(View.GONE);
425 tvAccount.setLayoutParams(accountParams);
426 amountLayout.setLayoutParams(amountLayoutParams);
428 transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
431 amountValidityObserver = valid -> {
432 tvAmount.setCompoundDrawablesRelativeWithIntrinsicBounds(
433 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
434 tvAmount.setMinEms(valid ? 4 : 5);
437 private void commentFocusChanged(TextView textView, boolean hasFocus) {
438 @ColorInt int textColor;
439 textColor = tvDummy.getTextColors()
442 textView.setTypeface(null, Typeface.NORMAL);
443 textView.setHint(R.string.transaction_account_comment_hint);
446 int alpha = (textColor >> 24 & 0xff);
447 alpha = 3 * alpha / 4;
448 textColor = (alpha << 24) | (0x00ffffff & textColor);
449 textView.setTypeface(null, Typeface.ITALIC);
450 textView.setHint("");
451 if (TextUtils.isEmpty(textView.getText())) {
452 textView.setVisibility(View.INVISIBLE);
455 textView.setTextColor(textColor);
458 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
459 ConstraintLayout.LayoutParams amountLP =
460 (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
461 ConstraintLayout.LayoutParams currencyLP =
462 (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
464 if (position == Currency.Position.before) {
465 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
466 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
468 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
469 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
470 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
471 amountLP.startToEnd = tvCurrency.getId();
473 tvCurrency.setGravity(Gravity.END);
476 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
477 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
479 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
480 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
481 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
482 amountLP.endToStart = tvCurrency.getId();
484 tvCurrency.setGravity(Gravity.START);
487 amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
488 currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
490 tvAmount.setLayoutParams(amountLP);
491 tvCurrency.setLayoutParams(currencyLP);
493 // distance between the amount and the currency symbol
494 int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
496 if (position == Currency.Position.before) {
497 tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
500 tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
503 private void setCurrencyString(String currency) {
504 @ColorInt int textColor = tvDummy.getTextColors()
506 if ((currency == null) || currency.isEmpty()) {
507 tvCurrency.setText(R.string.currency_symbol);
508 int alpha = (textColor >> 24) & 0xff;
509 alpha = alpha * 3 / 4;
510 tvCurrency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
513 tvCurrency.setText(currency);
514 tvCurrency.setTextColor(textColor);
517 private void setCurrency(Currency currency) {
518 setCurrencyString((currency == null) ? null : currency.getName());
520 private void setEditable(Boolean editable) {
521 tvDate.setEnabled(editable);
522 tvDescription.setEnabled(editable);
523 tvAccount.setEnabled(editable);
524 tvAmount.setEnabled(editable);
526 private void beginUpdates() {
528 throw new RuntimeException("Already in update mode");
531 private void endUpdates() {
533 throw new RuntimeException("Not in update mode");
539 * Stores the data from the UI elements into the model item
540 * Returns true if there were changes made that suggest transaction has to be
541 * checked for being submittable
543 private boolean syncData() {
548 Logger.debug("new-trans", "skipping syncData() loop");
555 switch (item.getType()) {
557 item.setDate(String.valueOf(tvDate.getText()));
558 item.setDescription(String.valueOf(tvDescription.getText()));
559 item.setTransactionComment(String.valueOf(tvTransactionComment.getText()));
562 final LedgerTransactionAccount account = item.getAccount();
563 account.setAccountName(String.valueOf(tvAccount.getText()));
565 item.setComment(String.valueOf(tvComment.getText()));
567 String amount = String.valueOf(tvAmount.getText());
568 amount = amount.trim();
570 if (amount.isEmpty()) {
571 account.resetAmount();
572 item.validateAmount();
576 amount = amount.replace(decimalSeparator, decimalDot);
577 account.setAmount(Float.parseFloat(amount));
578 item.validateAmount();
580 catch (NumberFormatException e) {
581 Logger.debug("new-trans", String.format(
582 "assuming amount is not set due to number format exception. " +
583 "input was '%s'", amount));
584 account.invalidateAmount();
585 item.invalidateAmount();
587 final String curr = String.valueOf(tvCurrency.getText());
588 if (curr.equals(tvCurrency.getContext()
590 .getString(R.string.currency_symbol)) ||
592 account.setCurrency(null);
594 account.setCurrency(curr);
599 throw new RuntimeException("Should not happen");
604 catch (ParseException e) {
605 throw new RuntimeException("Should not happen", e);
611 private void pickTransactionDate() {
612 DatePickerFragment picker = new DatePickerFragment();
613 picker.setFutureDates(mProfile.getFutureDates());
614 picker.setOnDatePickedListener(this);
615 picker.setCurrentDateFromText(tvDate.getText());
616 picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
622 * @param item updates the UI elements with the data from the model item
624 @SuppressLint("DefaultLocale")
625 public void setData(NewTransactionModel.Item item) {
628 if (this.item != null && !this.item.equals(item)) {
629 this.item.stopObservingDate(dateObserver);
630 this.item.stopObservingDescription(descriptionObserver);
631 this.item.stopObservingTransactionComment(transactionCommentObserver);
632 this.item.stopObservingAmountHint(hintObserver);
633 this.item.stopObservingEditableFlag(editableObserver);
635 .stopObservingFocusedItem(focusedAccountObserver);
637 .stopObservingAccountCount(accountCountObserver);
638 Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
639 Data.currencyGap.removeObserver(currencyGapObserver);
640 Data.locale.removeObserver(localeObserver);
641 this.item.stopObservingCurrency(currencyObserver);
642 this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
643 this.item.stopObservingComment(commentObserver);
644 this.item.getModel().showComments.removeObserver(showCommentsObserver);
645 this.item.stopObservingAmountValidity(amountValidityObserver);
650 switch (item.getType()) {
652 tvDate.setText(item.getFormattedDate());
653 tvDescription.setText(item.getDescription());
654 tvTransactionComment.setText(item.getTransactionComment());
655 lHead.setVisibility(View.VISIBLE);
656 lAccount.setVisibility(View.GONE);
657 lPadding.setVisibility(View.GONE);
661 LedgerTransactionAccount acc = item.getAccount();
662 tvAccount.setText(acc.getAccountName());
663 tvComment.setText(acc.getComment());
664 if (acc.isAmountSet()) {
665 tvAmount.setText(String.format("%1.2f", acc.getAmount()));
668 tvAmount.setText("");
669 // tvAmount.setHint(R.string.zero_amount);
671 tvAmount.setHint(item.getAmountHint());
672 setCurrencyString(acc.getCurrency());
673 lHead.setVisibility(View.GONE);
674 lAccount.setVisibility(View.VISIBLE);
675 lPadding.setVisibility(View.GONE);
679 lHead.setVisibility(View.GONE);
680 lAccount.setVisibility(View.GONE);
681 lPadding.setVisibility(View.VISIBLE);
685 if (this.item == null) { // was null or has changed
687 final NewTransactionActivity activity =
688 (NewTransactionActivity) tvDescription.getContext();
690 if (!item.isBottomFiller()) {
691 item.observeEditableFlag(activity, editableObserver);
693 .observeFocusedItem(activity, focusedAccountObserver);
695 .observeShowComments(activity, showCommentsObserver);
697 switch (item.getType()) {
699 item.observeDate(activity, dateObserver);
700 item.observeDescription(activity, descriptionObserver);
701 item.observeTransactionComment(activity, transactionCommentObserver);
704 item.observeAmountHint(activity, hintObserver);
705 Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
706 Data.currencyGap.observe(activity, currencyGapObserver);
707 Data.locale.observe(activity, localeObserver);
708 item.observeCurrency(activity, currencyObserver);
709 item.getModel().showCurrency.observe(activity, showCurrencyObserver);
710 item.observeComment(activity, commentObserver);
712 .observeAccountCount(activity, accountCountObserver);
713 item.observeAmountValidity(activity, amountValidityObserver);
723 public void onDatePicked(int year, int month, int day) {
724 item.setDate(new SimpleDate(year, month + 1, day));
725 boolean focused = tvDescription.requestFocus();
727 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
731 public void descriptionSelected(String description) {
732 tvAccount.setText(description);
733 tvAmount.requestFocus(View.FOCUS_FORWARD);