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.TextWatcher;
24 import android.view.Gravity;
25 import android.view.View;
26 import android.view.ViewGroup;
27 import android.view.inputmethod.EditorInfo;
28 import android.widget.AutoCompleteTextView;
29 import android.widget.EditText;
30 import android.widget.FrameLayout;
31 import android.widget.TextView;
33 import androidx.annotation.ColorInt;
34 import androidx.annotation.NonNull;
35 import androidx.appcompat.app.AppCompatActivity;
36 import androidx.constraintlayout.widget.ConstraintLayout;
37 import androidx.lifecycle.Observer;
38 import androidx.recyclerview.widget.RecyclerView;
40 import net.ktnx.mobileledger.R;
41 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
42 import net.ktnx.mobileledger.model.Currency;
43 import net.ktnx.mobileledger.model.Data;
44 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
45 import net.ktnx.mobileledger.model.MobileLedgerProfile;
46 import net.ktnx.mobileledger.ui.CurrencySelectorFragment;
47 import net.ktnx.mobileledger.ui.DatePickerFragment;
48 import net.ktnx.mobileledger.ui.TextViewClearHelper;
49 import net.ktnx.mobileledger.utils.DimensionUtils;
50 import net.ktnx.mobileledger.utils.Logger;
51 import net.ktnx.mobileledger.utils.MLDB;
52 import net.ktnx.mobileledger.utils.Misc;
53 import net.ktnx.mobileledger.utils.SimpleDate;
55 import java.text.DecimalFormatSymbols;
56 import java.text.ParseException;
57 import java.util.Date;
58 import java.util.Locale;
60 import static net.ktnx.mobileledger.ui.activity.NewTransactionModel.ItemType;
62 class NewTransactionItemHolder extends RecyclerView.ViewHolder
63 implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback {
64 private final String decimalDot;
65 private final TextView tvCurrency;
66 private final Observer<Boolean> showCommentsObserver;
67 private final TextView tvTransactionComment;
68 private String decimalSeparator;
69 private NewTransactionModel.Item item;
70 private TextView tvDate;
71 private AutoCompleteTextView tvDescription;
72 private TextView tvDummy;
73 private AutoCompleteTextView tvAccount;
74 private TextView tvComment;
75 private EditText tvAmount;
76 private ViewGroup lHead;
77 private ViewGroup lAccount;
78 private FrameLayout lPadding;
79 private MobileLedgerProfile mProfile;
81 private Observer<SimpleDate> dateObserver;
82 private Observer<String> descriptionObserver;
83 private Observer<String> transactionCommentObserver;
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 Observer<Boolean> amountValidityObserver;
95 private boolean inUpdate = false;
96 private boolean syncingData = false;
97 private View commentButton;
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 commentButton = lAccount.findViewById(R.id.comment_button);
107 tvAmount = itemView.findViewById(R.id.account_row_acc_amounts);
108 tvCurrency = itemView.findViewById(R.id.currency);
109 tvDate = itemView.findViewById(R.id.new_transaction_date);
110 tvDescription = itemView.findViewById(R.id.new_transaction_description);
111 tvDummy = itemView.findViewById(R.id.dummy_text);
112 lHead = itemView.findViewById(R.id.ntr_data);
113 lPadding = itemView.findViewById(R.id.ntr_padding);
114 final View commentLayout = itemView.findViewById(R.id.comment_layout);
115 final View transactionCommentLayout =
116 itemView.findViewById(R.id.transaction_comment_layout);
118 tvDescription.setNextFocusForwardId(View.NO_ID);
119 tvAccount.setNextFocusForwardId(View.NO_ID);
120 tvAmount.setNextFocusForwardId(View.NO_ID); // magic!
122 tvDate.setOnClickListener(v -> pickTransactionDate());
124 commentButton.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(((focusedView != tvTransactionComment) &&
275 Misc.isEmptyOrNull(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);
383 tvCurrency.setVisibility(View.GONE);
384 item.setCurrency(null);
388 commentObserver = comment -> {
389 final View focusedView = tvComment.findFocus();
390 tvComment.setTypeface(null,
391 (focusedView == tvComment) ? Typeface.NORMAL : Typeface.ITALIC);
392 tvComment.setVisibility(
393 ((focusedView != tvComment) && Misc.isEmptyOrNull(comment)) ? View.INVISIBLE
397 showCommentsObserver = show -> {
398 final View amountLayout = itemView.findViewById(R.id.amount_layout);
399 ConstraintLayout.LayoutParams amountLayoutParams =
400 (ConstraintLayout.LayoutParams) amountLayout.getLayoutParams();
401 ConstraintLayout.LayoutParams accountParams =
402 (ConstraintLayout.LayoutParams) tvAccount.getLayoutParams();
404 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
405 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
407 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
408 amountLayoutParams.topToBottom = tvAccount.getId();
410 commentLayout.setVisibility(View.VISIBLE);
413 accountParams.endToStart = amountLayout.getId();
414 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
416 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
417 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
419 commentLayout.setVisibility(View.GONE);
422 tvAccount.setLayoutParams(accountParams);
423 amountLayout.setLayoutParams(amountLayoutParams);
425 transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
428 amountValidityObserver = valid -> {
429 tvAmount.setCompoundDrawablesRelativeWithIntrinsicBounds(
430 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
431 tvAmount.setMinEms(valid ? 4 : 5);
434 private void commentFocusChanged(TextView textView, boolean hasFocus) {
435 @ColorInt int textColor;
436 textColor = tvDummy.getTextColors()
439 textView.setTypeface(null, Typeface.NORMAL);
440 textView.setHint(R.string.transaction_account_comment_hint);
443 int alpha = (textColor >> 24 & 0xff);
444 alpha = 3 * alpha / 4;
445 textColor = (alpha << 24) | (0x00ffffff & textColor);
446 textView.setTypeface(null, Typeface.ITALIC);
447 textView.setHint("");
448 if (Misc.isEmptyOrNull(textView.getText())) {
449 textView.setVisibility(View.INVISIBLE);
452 textView.setTextColor(textColor);
455 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
456 ConstraintLayout.LayoutParams amountLP =
457 (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
458 ConstraintLayout.LayoutParams currencyLP =
459 (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
461 if (position == Currency.Position.before) {
462 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
463 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
465 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
466 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
467 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
468 amountLP.startToEnd = tvCurrency.getId();
470 tvCurrency.setGravity(Gravity.END);
473 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
474 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
476 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
477 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
478 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
479 amountLP.endToStart = tvCurrency.getId();
481 tvCurrency.setGravity(Gravity.START);
484 amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
485 currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
487 tvAmount.setLayoutParams(amountLP);
488 tvCurrency.setLayoutParams(currencyLP);
490 // distance between the amount and the currency symbol
491 int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
493 if (position == Currency.Position.before) {
494 tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
497 tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
500 private void setCurrencyString(String currency) {
501 @ColorInt int textColor = tvDummy.getTextColors()
503 if ((currency == null) || currency.isEmpty()) {
504 tvCurrency.setText(R.string.currency_symbol);
505 int alpha = (textColor >> 24) & 0xff;
506 alpha = alpha * 3 / 4;
507 tvCurrency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
510 tvCurrency.setText(currency);
511 tvCurrency.setTextColor(textColor);
514 private void setCurrency(Currency currency) {
515 setCurrencyString((currency == null) ? null : currency.getName());
517 private void setEditable(Boolean editable) {
518 tvDate.setEnabled(editable);
519 tvDescription.setEnabled(editable);
520 tvAccount.setEnabled(editable);
521 tvAmount.setEnabled(editable);
523 private void beginUpdates() {
525 throw new RuntimeException("Already in update mode");
528 private void endUpdates() {
530 throw new RuntimeException("Not in update mode");
536 * Stores the data from the UI elements into the model item
537 * Returns true if there were changes made that suggest transaction has to be
538 * checked for being submittable
540 private boolean syncData() {
545 Logger.debug("new-trans", "skipping syncData() loop");
552 switch (item.getType()) {
554 item.setDate(String.valueOf(tvDate.getText()));
555 item.setDescription(String.valueOf(tvDescription.getText()));
556 item.setTransactionComment(String.valueOf(tvTransactionComment.getText()));
559 final LedgerTransactionAccount account = item.getAccount();
560 account.setAccountName(String.valueOf(tvAccount.getText()));
562 item.setComment(String.valueOf(tvComment.getText()));
564 String amount = String.valueOf(tvAmount.getText());
565 amount = amount.trim();
567 if (amount.isEmpty()) {
568 account.resetAmount();
569 item.validateAmount();
573 amount = amount.replace(decimalSeparator, decimalDot);
574 account.setAmount(Float.parseFloat(amount));
575 item.validateAmount();
577 catch (NumberFormatException e) {
578 Logger.debug("new-trans", String.format(
579 "assuming amount is not set due to number format exception. " +
580 "input was '%s'", amount));
581 account.invalidateAmount();
582 item.invalidateAmount();
584 final String curr = String.valueOf(tvCurrency.getText());
585 if (curr.equals(tvCurrency.getContext()
587 .getString(R.string.currency_symbol)) ||
589 account.setCurrency(null);
591 account.setCurrency(curr);
596 throw new RuntimeException("Should not happen");
601 catch (ParseException e) {
602 throw new RuntimeException("Should not happen", e);
608 private void pickTransactionDate() {
609 DatePickerFragment picker = new DatePickerFragment();
610 picker.setFutureDates(mProfile.getFutureDates());
611 picker.setOnDatePickedListener(this);
612 picker.setCurrentDateFromText(tvDate.getText());
613 picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
619 * @param item updates the UI elements with the data from the model item
621 @SuppressLint("DefaultLocale")
622 public void setData(NewTransactionModel.Item item) {
625 if (this.item != null && !this.item.equals(item)) {
626 this.item.stopObservingDate(dateObserver);
627 this.item.stopObservingDescription(descriptionObserver);
628 this.item.stopObservingTransactionComment(transactionCommentObserver);
629 this.item.stopObservingAmountHint(hintObserver);
630 this.item.stopObservingEditableFlag(editableObserver);
632 .stopObservingFocusedItem(focusedAccountObserver);
634 .stopObservingAccountCount(accountCountObserver);
635 Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
636 Data.currencyGap.removeObserver(currencyGapObserver);
637 Data.locale.removeObserver(localeObserver);
638 this.item.stopObservingCurrency(currencyObserver);
639 this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
640 this.item.stopObservingComment(commentObserver);
641 this.item.getModel().showComments.removeObserver(showCommentsObserver);
642 this.item.stopObservingAmountValidity(amountValidityObserver);
647 switch (item.getType()) {
649 tvDate.setText(item.getFormattedDate());
650 tvDescription.setText(item.getDescription());
651 tvTransactionComment.setText(item.getTransactionComment());
652 lHead.setVisibility(View.VISIBLE);
653 lAccount.setVisibility(View.GONE);
654 lPadding.setVisibility(View.GONE);
658 LedgerTransactionAccount acc = item.getAccount();
659 tvAccount.setText(acc.getAccountName());
660 tvComment.setText(acc.getComment());
661 if (acc.isAmountSet()) {
662 tvAmount.setText(String.format("%1.2f", acc.getAmount()));
665 tvAmount.setText("");
666 // tvAmount.setHint(R.string.zero_amount);
668 tvAmount.setHint(item.getAmountHint());
669 setCurrencyString(acc.getCurrency());
670 lHead.setVisibility(View.GONE);
671 lAccount.setVisibility(View.VISIBLE);
672 lPadding.setVisibility(View.GONE);
676 lHead.setVisibility(View.GONE);
677 lAccount.setVisibility(View.GONE);
678 lPadding.setVisibility(View.VISIBLE);
682 if (this.item == null) { // was null or has changed
684 final NewTransactionActivity activity =
685 (NewTransactionActivity) tvDescription.getContext();
687 if (!item.isOfType(ItemType.bottomFiller)) {
688 item.observeEditableFlag(activity, editableObserver);
690 .observeFocusedItem(activity, focusedAccountObserver);
692 .observeShowComments(activity, showCommentsObserver);
694 switch (item.getType()) {
696 item.observeDate(activity, dateObserver);
697 item.observeDescription(activity, descriptionObserver);
698 item.observeTransactionComment(activity, transactionCommentObserver);
701 item.observeAmountHint(activity, hintObserver);
702 Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
703 Data.currencyGap.observe(activity, currencyGapObserver);
704 Data.locale.observe(activity, localeObserver);
705 item.observeCurrency(activity, currencyObserver);
706 item.getModel().showCurrency.observe(activity, showCurrencyObserver);
707 item.observeComment(activity, commentObserver);
709 .observeAccountCount(activity, accountCountObserver);
710 item.observeAmountValidity(activity, amountValidityObserver);
720 public void onDatePicked(int year, int month, int day) {
721 item.setDate(new SimpleDate(year, month + 1, day));
722 boolean focused = tvDescription.requestFocus();
724 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
728 public void descriptionSelected(String description) {
729 tvAccount.setText(description);
730 tvAmount.requestFocus(View.FOCUS_FORWARD);