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 //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 tvAmount = itemView.findViewById(R.id.account_row_acc_amounts);
106 tvCurrency = itemView.findViewById(R.id.currency);
107 tvDate = itemView.findViewById(R.id.new_transaction_date);
108 tvDescription = itemView.findViewById(R.id.new_transaction_description);
109 tvDummy = itemView.findViewById(R.id.dummy_text);
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 lAccount.findViewById(R.id.comment_button)
123 .setOnClickListener(v -> {
124 tvComment.setVisibility(View.VISIBLE);
125 tvComment.requestFocus();
128 transactionCommentLayout.findViewById(R.id.comment_button)
129 .setOnClickListener(v -> {
130 tvTransactionComment.setVisibility(View.VISIBLE);
131 tvTransactionComment.requestFocus();
134 mProfile = Data.getProfile();
136 View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
137 final int id = v.getId();
139 boolean wasSyncing = syncingData;
142 final int pos = getAdapterPosition();
143 adapter.updateFocusedItem(pos);
145 case R.id.account_row_acc_name:
146 adapter.noteFocusIsOnAccount(pos);
148 case R.id.account_row_acc_amounts:
149 adapter.noteFocusIsOnAmount(pos);
152 adapter.noteFocusIsOnComment(pos);
154 case R.id.transaction_comment:
155 adapter.noteFocusIsOnTransactionComment(pos);
157 case R.id.new_transaction_description:
158 adapter.noteFocusIsOnDescription(pos);
163 syncingData = wasSyncing;
167 if (id == R.id.comment) {
168 commentFocusChanged(tvComment, hasFocus);
170 else if (id == R.id.transaction_comment) {
171 commentFocusChanged(tvTransactionComment, hasFocus);
175 tvDescription.setOnFocusChangeListener(focusMonitor);
176 tvAccount.setOnFocusChangeListener(focusMonitor);
177 tvAmount.setOnFocusChangeListener(focusMonitor);
178 tvComment.setOnFocusChangeListener(focusMonitor);
179 tvTransactionComment.setOnFocusChangeListener(focusMonitor);
181 MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
182 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
183 MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
184 "name", true, this, mProfile);
186 decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
187 .getMonetaryDecimalSeparator());
188 localeObserver = locale -> decimalSeparator = String.valueOf(
189 DecimalFormatSymbols.getInstance(locale)
190 .getMonetaryDecimalSeparator());
194 final TextWatcher tw = new TextWatcher() {
196 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
200 public void onTextChanged(CharSequence s, int start, int before, int count) {
204 public void afterTextChanged(Editable s) {
205 // debug("input", "text changed");
209 Logger.debug("textWatcher", "calling syncData()");
211 Logger.debug("textWatcher",
212 "syncData() returned, checking if transaction is submittable");
213 adapter.checkTransactionSubmittable();
214 Logger.debug("textWatcher", "done");
217 final TextWatcher amountWatcher = new TextWatcher() {
219 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
221 String.format(Locale.US, "beforeTextChanged: start=%d, count=%d, after=%d",
222 start, count, after));
225 public void onTextChanged(CharSequence s, int start, int before, int count) {}
227 public void afterTextChanged(Editable s) {
230 adapter.checkTransactionSubmittable();
233 tvDescription.addTextChangedListener(tw);
234 tvTransactionComment.addTextChangedListener(tw);
235 tvAccount.addTextChangedListener(tw);
236 tvComment.addTextChangedListener(tw);
237 tvAmount.addTextChangedListener(amountWatcher);
239 tvCurrency.setOnClickListener(v -> {
240 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
241 cpf.showPositionAndPadding();
242 cpf.setOnCurrencySelectedListener(c -> item.setCurrency(c));
243 final AppCompatActivity activity = (AppCompatActivity) v.getContext();
244 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
247 dateObserver = date -> {
252 tvDate.setText(item.getFormattedDate());
258 descriptionObserver = description -> {
263 tvDescription.setText(description);
269 transactionCommentObserver = transactionComment -> {
270 final View focusedView = tvTransactionComment.findFocus();
271 tvTransactionComment.setTypeface(null,
272 (focusedView == tvTransactionComment) ? Typeface.NORMAL : Typeface.ITALIC);
273 tvTransactionComment.setVisibility(((focusedView != tvTransactionComment) &&
274 Misc.isEmptyOrNull(transactionComment))
275 ? View.INVISIBLE : View.VISIBLE);
278 hintObserver = hint -> {
284 tvAmount.setHint(R.string.zero_amount);
286 tvAmount.setHint(hint);
292 editableObserver = this::setEditable;
293 commentFocusChanged(tvTransactionComment, false);
294 commentFocusChanged(tvComment, false);
295 focusedAccountObserver = index -> {
296 if ((index == null) || !index.equals(getAdapterPosition()) || itemView.hasFocus())
299 switch (item.getType()) {
301 // bad idea - double pop-up, and not really necessary.
302 // the user can tap the input to get the calendar
303 //if (!tvDate.hasFocus()) tvDate.requestFocus();
304 switch (item.getFocusedElement()) {
305 case TransactionComment:
306 tvTransactionComment.setVisibility(View.VISIBLE);
307 tvTransactionComment.requestFocus();
310 boolean focused = tvDescription.requestFocus();
311 tvDescription.dismissDropDown();
313 Misc.showSoftKeyboard(
314 (NewTransactionActivity) tvDescription.getContext());
319 switch (item.getFocusedElement()) {
321 tvAmount.requestFocus();
324 tvComment.setVisibility(View.VISIBLE);
325 tvComment.requestFocus();
328 boolean focused = tvAccount.requestFocus();
329 tvAccount.dismissDropDown();
331 Misc.showSoftKeyboard(
332 (NewTransactionActivity) tvAccount.getContext());
339 accountCountObserver = count -> {
340 final int adapterPosition = getAdapterPosition();
341 final int layoutPosition = getLayoutPosition();
342 Logger.debug("holder",
343 String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
344 adapterPosition, layoutPosition, item.getType()
346 .concat(item.getType() ==
347 ItemType.transactionRow
348 ? String.format(Locale.US,
354 ? String.format(Locale.US,
359 if (adapterPosition == count)
360 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
362 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
365 currencyObserver = currency -> {
366 setCurrency(currency);
367 adapter.checkTransactionSubmittable();
370 currencyGapObserver =
371 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
374 currencyPositionObserver =
375 position -> updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
377 showCurrencyObserver = showCurrency -> {
379 tvCurrency.setVisibility(View.VISIBLE);
382 tvCurrency.setVisibility(View.GONE);
383 item.setCurrency(null);
387 commentObserver = comment -> {
388 final View focusedView = tvComment.findFocus();
389 tvComment.setTypeface(null,
390 (focusedView == tvComment) ? Typeface.NORMAL : Typeface.ITALIC);
391 tvComment.setVisibility(
392 ((focusedView != tvComment) && Misc.isEmptyOrNull(comment)) ? View.INVISIBLE
396 showCommentsObserver = show -> {
397 final View amountLayout = itemView.findViewById(R.id.amount_layout);
398 ConstraintLayout.LayoutParams amountLayoutParams =
399 (ConstraintLayout.LayoutParams) amountLayout.getLayoutParams();
400 ConstraintLayout.LayoutParams accountParams =
401 (ConstraintLayout.LayoutParams) tvAccount.getLayoutParams();
403 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
404 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
406 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
407 amountLayoutParams.topToBottom = tvAccount.getId();
409 commentLayout.setVisibility(View.VISIBLE);
412 accountParams.endToStart = amountLayout.getId();
413 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
415 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
416 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
418 commentLayout.setVisibility(View.GONE);
421 tvAccount.setLayoutParams(accountParams);
422 amountLayout.setLayoutParams(amountLayoutParams);
424 transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
427 amountValidityObserver = valid -> {
428 tvAmount.setCompoundDrawablesRelativeWithIntrinsicBounds(
429 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
430 tvAmount.setMinEms(valid ? 4 : 5);
433 private void commentFocusChanged(TextView textView, boolean hasFocus) {
434 @ColorInt int textColor;
435 textColor = tvDummy.getTextColors()
438 textView.setTypeface(null, Typeface.NORMAL);
439 textView.setHint(R.string.transaction_account_comment_hint);
442 int alpha = (textColor >> 24 & 0xff);
443 alpha = 3 * alpha / 4;
444 textColor = (alpha << 24) | (0x00ffffff & textColor);
445 textView.setTypeface(null, Typeface.ITALIC);
446 textView.setHint("");
447 if (Misc.isEmptyOrNull(textView.getText())) {
448 textView.setVisibility(View.INVISIBLE);
451 textView.setTextColor(textColor);
454 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
455 ConstraintLayout.LayoutParams amountLP =
456 (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
457 ConstraintLayout.LayoutParams currencyLP =
458 (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
460 if (position == Currency.Position.before) {
461 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
462 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
464 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
465 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
466 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
467 amountLP.startToEnd = tvCurrency.getId();
469 tvCurrency.setGravity(Gravity.END);
472 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
473 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
475 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
476 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
477 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
478 amountLP.endToStart = tvCurrency.getId();
480 tvCurrency.setGravity(Gravity.START);
483 amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
484 currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
486 tvAmount.setLayoutParams(amountLP);
487 tvCurrency.setLayoutParams(currencyLP);
489 // distance between the amount and the currency symbol
490 int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
492 if (position == Currency.Position.before) {
493 tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
496 tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
499 private void setCurrencyString(String currency) {
500 @ColorInt int textColor = tvDummy.getTextColors()
502 if ((currency == null) || currency.isEmpty()) {
503 tvCurrency.setText(R.string.currency_symbol);
504 int alpha = (textColor >> 24) & 0xff;
505 alpha = alpha * 3 / 4;
506 tvCurrency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
509 tvCurrency.setText(currency);
510 tvCurrency.setTextColor(textColor);
513 private void setCurrency(Currency currency) {
514 setCurrencyString((currency == null) ? null : currency.getName());
516 private void setEditable(Boolean editable) {
517 tvDate.setEnabled(editable);
518 tvDescription.setEnabled(editable);
519 tvAccount.setEnabled(editable);
520 tvAmount.setEnabled(editable);
522 private void beginUpdates() {
524 throw new RuntimeException("Already in update mode");
527 private void endUpdates() {
529 throw new RuntimeException("Not in update mode");
535 * Stores the data from the UI elements into the model item
536 * Returns true if there were changes made that suggest transaction has to be
537 * checked for being submittable
539 private boolean syncData() {
544 Logger.debug("new-trans", "skipping syncData() loop");
551 switch (item.getType()) {
553 item.setDate(String.valueOf(tvDate.getText()));
554 item.setDescription(String.valueOf(tvDescription.getText()));
555 item.setTransactionComment(String.valueOf(tvTransactionComment.getText()));
558 final LedgerTransactionAccount account = item.getAccount();
559 account.setAccountName(String.valueOf(tvAccount.getText()));
561 item.setComment(String.valueOf(tvComment.getText()));
563 String amount = String.valueOf(tvAmount.getText());
564 amount = amount.trim();
566 if (amount.isEmpty()) {
567 account.resetAmount();
568 item.validateAmount();
572 amount = amount.replace(decimalSeparator, decimalDot);
573 account.setAmount(Float.parseFloat(amount));
574 item.validateAmount();
576 catch (NumberFormatException e) {
577 Logger.debug("new-trans", String.format(
578 "assuming amount is not set due to number format exception. " +
579 "input was '%s'", amount));
580 account.invalidateAmount();
581 item.invalidateAmount();
583 final String curr = String.valueOf(tvCurrency.getText());
584 if (curr.equals(tvCurrency.getContext()
586 .getString(R.string.currency_symbol)) ||
588 account.setCurrency(null);
590 account.setCurrency(curr);
595 throw new RuntimeException("Should not happen");
600 catch (ParseException e) {
601 throw new RuntimeException("Should not happen", e);
607 private void pickTransactionDate() {
608 DatePickerFragment picker = new DatePickerFragment();
609 picker.setFutureDates(mProfile.getFutureDates());
610 picker.setOnDatePickedListener(this);
611 picker.setCurrentDateFromText(tvDate.getText());
612 picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
618 * @param item updates the UI elements with the data from the model item
620 @SuppressLint("DefaultLocale")
621 public void setData(NewTransactionModel.Item item) {
624 if (this.item != null && !this.item.equals(item)) {
625 this.item.stopObservingDate(dateObserver);
626 this.item.stopObservingDescription(descriptionObserver);
627 this.item.stopObservingTransactionComment(transactionCommentObserver);
628 this.item.stopObservingAmountHint(hintObserver);
629 this.item.stopObservingEditableFlag(editableObserver);
631 .stopObservingFocusedItem(focusedAccountObserver);
633 .stopObservingAccountCount(accountCountObserver);
634 Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
635 Data.currencyGap.removeObserver(currencyGapObserver);
636 Data.locale.removeObserver(localeObserver);
637 this.item.stopObservingCurrency(currencyObserver);
638 this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
639 this.item.stopObservingComment(commentObserver);
640 this.item.getModel().showComments.removeObserver(showCommentsObserver);
641 this.item.stopObservingAmountValidity(amountValidityObserver);
646 switch (item.getType()) {
648 tvDate.setText(item.getFormattedDate());
649 tvDescription.setText(item.getDescription());
650 tvTransactionComment.setText(item.getTransactionComment());
651 lHead.setVisibility(View.VISIBLE);
652 lAccount.setVisibility(View.GONE);
653 lPadding.setVisibility(View.GONE);
657 LedgerTransactionAccount acc = item.getAccount();
658 tvAccount.setText(acc.getAccountName());
659 tvComment.setText(acc.getComment());
660 if (acc.isAmountSet()) {
661 tvAmount.setText(String.format("%1.2f", acc.getAmount()));
664 tvAmount.setText("");
665 // tvAmount.setHint(R.string.zero_amount);
667 tvAmount.setHint(item.getAmountHint());
668 setCurrencyString(acc.getCurrency());
669 lHead.setVisibility(View.GONE);
670 lAccount.setVisibility(View.VISIBLE);
671 lPadding.setVisibility(View.GONE);
675 lHead.setVisibility(View.GONE);
676 lAccount.setVisibility(View.GONE);
677 lPadding.setVisibility(View.VISIBLE);
681 if (this.item == null) { // was null or has changed
683 final NewTransactionActivity activity =
684 (NewTransactionActivity) tvDescription.getContext();
686 if (!item.isOfType(ItemType.bottomFiller)) {
687 item.observeEditableFlag(activity, editableObserver);
689 .observeFocusedItem(activity, focusedAccountObserver);
691 .observeShowComments(activity, showCommentsObserver);
693 switch (item.getType()) {
695 item.observeDate(activity, dateObserver);
696 item.observeDescription(activity, descriptionObserver);
697 item.observeTransactionComment(activity, transactionCommentObserver);
700 item.observeAmountHint(activity, hintObserver);
701 Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
702 Data.currencyGap.observe(activity, currencyGapObserver);
703 Data.locale.observe(activity, localeObserver);
704 item.observeCurrency(activity, currencyObserver);
705 item.getModel().showCurrency.observe(activity, showCurrencyObserver);
706 item.observeComment(activity, commentObserver);
708 .observeAccountCount(activity, accountCountObserver);
709 item.observeAmountValidity(activity, amountValidityObserver);
719 public void onDatePicked(int year, int month, int day) {
720 item.setDate(new SimpleDate(year, month + 1, day));
721 boolean focused = tvDescription.requestFocus();
723 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
727 public void descriptionSelected(String description) {
728 tvAccount.setText(description);
729 tvAmount.requestFocus(View.FOCUS_FORWARD);