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.Colors;
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 String decimalSeparator;
70 private NewTransactionModel.Item item;
71 private TextView tvDate;
72 private AutoCompleteTextView tvDescription;
73 private TextView tvDummy;
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<SimpleDate> dateObserver;
83 private Observer<String> descriptionObserver;
84 private Observer<String> transactionCommentObserver;
85 private Observer<String> hintObserver;
86 private Observer<Integer> focusedAccountObserver;
87 private Observer<Integer> accountCountObserver;
88 private Observer<Boolean> editableObserver;
89 private Observer<Currency.Position> currencyPositionObserver;
90 private Observer<Boolean> currencyGapObserver;
91 private Observer<Locale> localeObserver;
92 private Observer<Currency> currencyObserver;
93 private Observer<Boolean> showCurrencyObserver;
94 private Observer<String> commentObserver;
95 private Observer<Boolean> amountValidityObserver;
96 private boolean inUpdate = false;
97 private boolean syncingData = false;
98 private View commentButton;
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 commentButton = lAccount.findViewById(R.id.comment_button);
108 tvAmount = itemView.findViewById(R.id.account_row_acc_amounts);
109 tvCurrency = itemView.findViewById(R.id.currency);
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 commentButton.setOnClickListener(v -> {
126 tvComment.setVisibility(View.VISIBLE);
127 tvComment.requestFocus();
130 transactionCommentLayout.findViewById(R.id.comment_button)
131 .setOnClickListener(v -> {
132 tvTransactionComment.setVisibility(View.VISIBLE);
133 tvTransactionComment.requestFocus();
136 mProfile = Data.profile.getValue();
137 if (mProfile == null)
138 throw new AssertionError();
140 View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
141 final int id = v.getId();
143 boolean wasSyncing = syncingData;
146 final int pos = getAdapterPosition();
147 adapter.updateFocusedItem(pos);
149 case R.id.account_row_acc_name:
150 adapter.noteFocusIsOnAccount(pos);
152 case R.id.account_row_acc_amounts:
153 adapter.noteFocusIsOnAmount(pos);
156 adapter.noteFocusIsOnComment(pos);
158 case R.id.transaction_comment:
159 adapter.noteFocusIsOnTransactionComment(pos);
161 case R.id.new_transaction_description:
162 adapter.noteFocusIsOnDescription(pos);
167 syncingData = wasSyncing;
171 if (id == R.id.comment) {
172 commentFocusChanged(tvComment, hasFocus);
174 else if (id == R.id.transaction_comment) {
175 commentFocusChanged(tvTransactionComment, hasFocus);
179 tvDescription.setOnFocusChangeListener(focusMonitor);
180 tvAccount.setOnFocusChangeListener(focusMonitor);
181 tvAmount.setOnFocusChangeListener(focusMonitor);
182 tvComment.setOnFocusChangeListener(focusMonitor);
183 tvTransactionComment.setOnFocusChangeListener(focusMonitor);
185 MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
186 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
187 MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
188 "name", true, this, mProfile);
190 decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
191 .getMonetaryDecimalSeparator());
192 localeObserver = locale -> {
193 decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance(locale)
194 .getMonetaryDecimalSeparator());
199 final TextWatcher tw = new TextWatcher() {
201 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
205 public void onTextChanged(CharSequence s, int start, int before, int count) {
209 public void afterTextChanged(Editable s) {
210 // debug("input", "text changed");
214 Logger.debug("textWatcher", "calling syncData()");
216 Logger.debug("textWatcher",
217 "syncData() returned, checking if transaction is submittable");
218 adapter.checkTransactionSubmittable();
219 Logger.debug("textWatcher", "done");
222 final TextWatcher amountWatcher = new TextWatcher() {
224 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
226 String.format(Locale.US, "beforeTextChanged: start=%d, count=%d, after=%d",
227 start, count, after));
230 public void onTextChanged(CharSequence s, int start, int before, int count) {}
232 public void afterTextChanged(Editable s) {
235 adapter.checkTransactionSubmittable();
238 tvDescription.addTextChangedListener(tw);
239 tvTransactionComment.addTextChangedListener(tw);
240 tvAccount.addTextChangedListener(tw);
241 tvComment.addTextChangedListener(tw);
242 tvAmount.addTextChangedListener(amountWatcher);
244 tvCurrency.setOnClickListener(v -> {
245 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
246 cpf.showPositionAndPadding();
247 cpf.setOnCurrencySelectedListener(c -> item.setCurrency(c));
248 final AppCompatActivity activity = (AppCompatActivity) v.getContext();
249 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
252 dateObserver = date -> {
257 tvDate.setText(item.getFormattedDate());
263 descriptionObserver = description -> {
268 tvDescription.setText(description);
274 transactionCommentObserver = transactionComment -> {
275 final View focusedView = tvTransactionComment.findFocus();
276 tvTransactionComment.setTypeface(null,
277 (focusedView == tvTransactionComment) ? Typeface.NORMAL : Typeface.ITALIC);
278 tvTransactionComment.setVisibility(((focusedView != tvTransactionComment) &&
279 Misc.isEmptyOrNull(transactionComment))
280 ? View.INVISIBLE : View.VISIBLE);
283 hintObserver = hint -> {
289 tvAmount.setHint(R.string.zero_amount);
291 tvAmount.setHint(hint);
297 editableObserver = this::setEditable;
298 commentFocusChanged(tvTransactionComment, false);
299 commentFocusChanged(tvComment, false);
300 focusedAccountObserver = index -> {
301 if ((index == null) || !index.equals(getAdapterPosition()) || itemView.hasFocus())
304 switch (item.getType()) {
306 // bad idea - double pop-up, and not really necessary.
307 // the user can tap the input to get the calendar
308 //if (!tvDate.hasFocus()) tvDate.requestFocus();
309 switch (item.getFocusedElement()) {
310 case TransactionComment:
311 tvTransactionComment.setVisibility(View.VISIBLE);
312 tvTransactionComment.requestFocus();
315 boolean focused = tvDescription.requestFocus();
316 tvDescription.dismissDropDown();
318 Misc.showSoftKeyboard(
319 (NewTransactionActivity) tvDescription.getContext());
324 switch (item.getFocusedElement()) {
326 tvAmount.requestFocus();
329 tvComment.setVisibility(View.VISIBLE);
330 tvComment.requestFocus();
333 boolean focused = tvAccount.requestFocus();
334 tvAccount.dismissDropDown();
336 Misc.showSoftKeyboard(
337 (NewTransactionActivity) tvAccount.getContext());
344 accountCountObserver = count -> {
345 final int adapterPosition = getAdapterPosition();
346 final int layoutPosition = getLayoutPosition();
347 Logger.debug("holder",
348 String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
349 adapterPosition, layoutPosition, item.getType()
351 .concat(item.getType() ==
352 ItemType.transactionRow
353 ? String.format(Locale.US,
359 ? String.format(Locale.US,
364 if (adapterPosition == count)
365 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
367 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
370 currencyObserver = currency -> {
371 setCurrency(currency);
372 adapter.checkTransactionSubmittable();
375 currencyGapObserver =
376 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
379 currencyPositionObserver =
380 position -> updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
382 showCurrencyObserver = showCurrency -> {
384 tvCurrency.setVisibility(View.VISIBLE);
387 tvCurrency.setVisibility(View.GONE);
388 item.setCurrency(null);
392 commentObserver = comment -> {
393 final View focusedView = tvComment.findFocus();
394 tvComment.setTypeface(null,
395 (focusedView == tvComment) ? Typeface.NORMAL : Typeface.ITALIC);
396 tvComment.setVisibility(
397 ((focusedView != tvComment) && Misc.isEmptyOrNull(comment)) ? View.INVISIBLE
401 showCommentsObserver = show -> {
402 final View amountLayout = itemView.findViewById(R.id.amount_layout);
403 ConstraintLayout.LayoutParams amountLayoutParams =
404 (ConstraintLayout.LayoutParams) amountLayout.getLayoutParams();
405 ConstraintLayout.LayoutParams accountParams =
406 (ConstraintLayout.LayoutParams) tvAccount.getLayoutParams();
408 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
409 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
411 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
412 amountLayoutParams.topToBottom = tvAccount.getId();
414 commentLayout.setVisibility(View.VISIBLE);
417 accountParams.endToStart = amountLayout.getId();
418 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
420 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
421 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
423 commentLayout.setVisibility(View.GONE);
426 tvAccount.setLayoutParams(accountParams);
427 amountLayout.setLayoutParams(amountLayoutParams);
429 transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
432 amountValidityObserver = valid -> {
433 tvAmount.setCompoundDrawablesRelativeWithIntrinsicBounds(
434 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
435 tvAmount.setMinEms(valid ? 4 : 5);
438 private void commentFocusChanged(TextView textView, boolean hasFocus) {
439 @ColorInt int textColor;
440 textColor = tvDummy.getTextColors()
443 textView.setTypeface(null, Typeface.NORMAL);
444 textView.setHint(R.string.transaction_account_comment_hint);
447 int alpha = (textColor >> 24 & 0xff);
448 alpha = 3 * alpha / 4;
449 textColor = (alpha << 24) | (0x00ffffff & textColor);
450 textView.setTypeface(null, Typeface.ITALIC);
451 textView.setHint("");
452 if (Misc.isEmptyOrNull(textView.getText())) {
453 textView.setVisibility(View.INVISIBLE);
456 textView.setTextColor(textColor);
459 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
460 ConstraintLayout.LayoutParams amountLP =
461 (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
462 ConstraintLayout.LayoutParams currencyLP =
463 (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
465 if (position == Currency.Position.before) {
466 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
467 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
469 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
470 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
471 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
472 amountLP.startToEnd = tvCurrency.getId();
474 tvCurrency.setGravity(Gravity.END);
477 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
478 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
480 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
481 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
482 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
483 amountLP.endToStart = tvCurrency.getId();
485 tvCurrency.setGravity(Gravity.START);
488 amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
489 currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
491 tvAmount.setLayoutParams(amountLP);
492 tvCurrency.setLayoutParams(currencyLP);
494 // distance between the amount and the currency symbol
495 int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
497 if (position == Currency.Position.before) {
498 tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
501 tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
504 private void setCurrencyString(String currency) {
505 if ((currency == null) || currency.isEmpty()) {
506 tvCurrency.setText(R.string.currency_symbol);
507 tvCurrency.setTextColor(0x7f000000 + (0x00ffffff & Colors.defaultTextColor));
510 tvCurrency.setText(currency);
511 tvCurrency.setTextColor(Colors.defaultTextColor);
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);