2 * Copyright © 2019 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.os.Build;
23 import android.text.Editable;
24 import android.text.TextWatcher;
25 import android.text.method.DigitsKeyListener;
26 import android.view.Gravity;
27 import android.view.View;
28 import android.view.ViewGroup;
29 import android.view.inputmethod.EditorInfo;
30 import android.widget.AutoCompleteTextView;
31 import android.widget.EditText;
32 import android.widget.FrameLayout;
33 import android.widget.TextView;
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.Colors;
51 import net.ktnx.mobileledger.utils.DimensionUtils;
52 import net.ktnx.mobileledger.utils.Logger;
53 import net.ktnx.mobileledger.utils.MLDB;
54 import net.ktnx.mobileledger.utils.Misc;
56 import java.text.DecimalFormatSymbols;
57 import java.util.Calendar;
58 import java.util.Date;
59 import java.util.GregorianCalendar;
60 import java.util.Locale;
62 import static net.ktnx.mobileledger.ui.activity.NewTransactionModel.ItemType;
64 class NewTransactionItemHolder extends RecyclerView.ViewHolder
65 implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback {
66 private final String decimalDot;
67 private final TextView tvCurrency;
68 private final Observer<Boolean> showCommentsObserver;
69 private final TextView tvTransactionComment;
70 private String decimalSeparator;
71 private NewTransactionModel.Item item;
72 private TextView tvDate;
73 private AutoCompleteTextView tvDescription;
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<Date> 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 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.profile.getValue();
136 if (mProfile == null)
137 throw new AssertionError();
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(commentLayout, tvComment, hasFocus);
173 else if (id == R.id.transaction_comment) {
174 commentFocusChanged(transactionCommentLayout, 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 // updated on locale changes by an observer below
190 decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
191 .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 focusedAccountObserver = index -> {
294 if ((index == null) || !index.equals(getAdapterPosition()) || itemView.hasFocus())
297 switch (item.getType()) {
299 // bad idea - double pop-up, and not really necessary.
300 // the user can tap the input to get the calendar
301 //if (!tvDate.hasFocus()) tvDate.requestFocus();
302 switch (item.getFocusedElement()) {
303 case TransactionComment:
304 tvTransactionComment.setVisibility(View.VISIBLE);
305 tvTransactionComment.requestFocus();
308 boolean focused = tvDescription.requestFocus();
309 tvDescription.dismissDropDown();
311 Misc.showSoftKeyboard(
312 (NewTransactionActivity) tvDescription.getContext());
317 switch (item.getFocusedElement()) {
319 tvAmount.requestFocus();
322 tvComment.setVisibility(View.VISIBLE);
323 tvComment.requestFocus();
326 boolean focused = tvAccount.requestFocus();
327 tvAccount.dismissDropDown();
329 Misc.showSoftKeyboard(
330 (NewTransactionActivity) tvAccount.getContext());
337 accountCountObserver = count -> {
338 final int adapterPosition = getAdapterPosition();
339 final int layoutPosition = getLayoutPosition();
340 Logger.debug("holder",
341 String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
342 adapterPosition, layoutPosition, item.getType()
344 .concat(item.getType() ==
345 ItemType.transactionRow
346 ? String.format(Locale.US,
352 ? String.format(Locale.US,
357 if (adapterPosition == count)
358 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
360 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
363 localeObserver = locale -> {
364 decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance(locale)
365 .getMonetaryDecimalSeparator());
367 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
368 tvAmount.setKeyListener(DigitsKeyListener.getInstance(locale, true, true));
371 currencyObserver = currency -> {
372 setCurrency(currency);
373 adapter.checkTransactionSubmittable();
376 currencyGapObserver =
377 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
380 currencyPositionObserver =
381 position -> updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
383 showCurrencyObserver = showCurrency -> {
385 tvCurrency.setVisibility(View.VISIBLE);
388 tvCurrency.setVisibility(View.GONE);
389 item.setCurrency(null);
393 commentObserver = comment -> {
394 final View focusedView = tvComment.findFocus();
395 tvComment.setTypeface(null,
396 (focusedView == tvComment) ? Typeface.NORMAL : Typeface.ITALIC);
397 tvComment.setVisibility(
398 ((focusedView != tvComment) && Misc.isEmptyOrNull(comment)) ? View.INVISIBLE
402 showCommentsObserver = show -> {
403 final View amountLayout = itemView.findViewById(R.id.amount_layout);
404 ConstraintLayout.LayoutParams amountLayoutParams =
405 (ConstraintLayout.LayoutParams) amountLayout.getLayoutParams();
406 ConstraintLayout.LayoutParams accountParams =
407 (ConstraintLayout.LayoutParams) tvAccount.getLayoutParams();
409 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
410 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
412 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
413 amountLayoutParams.topToBottom = tvAccount.getId();
415 commentLayout.setVisibility(View.VISIBLE);
418 accountParams.endToStart = amountLayout.getId();
419 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
421 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
422 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
424 commentLayout.setVisibility(View.GONE);
427 tvAccount.setLayoutParams(accountParams);
428 amountLayout.setLayoutParams(amountLayoutParams);
430 transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
433 amountValidityObserver = valid -> {
434 tvAmount.setCompoundDrawablesRelativeWithIntrinsicBounds(
435 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
436 tvAmount.setMinEms(valid ? 4 : 5);
439 private void commentFocusChanged(View layout, TextView textView, boolean hasFocus) {
442 textColor = Colors.defaultTextColor;
443 textView.setTypeface(null, Typeface.NORMAL);
444 textView.setHint(R.string.transaction_account_comment_hint);
447 textColor = Colors.defaultTextColorDisabled;
448 textView.setTypeface(null, Typeface.ITALIC);
449 textView.setHint("");
450 if (Misc.isEmptyOrNull(textView.getText())) {
451 textView.setVisibility(View.INVISIBLE);
454 textView.setTextColor(textColor);
457 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
458 ConstraintLayout.LayoutParams amountLP =
459 (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
460 ConstraintLayout.LayoutParams currencyLP =
461 (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
463 if (position == Currency.Position.before) {
464 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
465 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
467 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
468 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
469 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
470 amountLP.startToEnd = tvCurrency.getId();
472 tvCurrency.setGravity(Gravity.END);
475 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
476 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
478 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
479 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
480 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
481 amountLP.endToStart = tvCurrency.getId();
483 tvCurrency.setGravity(Gravity.START);
486 amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
487 currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
489 tvAmount.setLayoutParams(amountLP);
490 tvCurrency.setLayoutParams(currencyLP);
492 // distance between the amount and the currency symbol
493 int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
495 if (position == Currency.Position.before) {
496 tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
499 tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
502 private void setCurrencyString(String currency) {
503 if ((currency == null) || currency.isEmpty()) {
504 tvCurrency.setText(R.string.currency_symbol);
505 tvCurrency.setTextColor(0x7f000000 + (0x00ffffff & Colors.defaultTextColor));
508 tvCurrency.setText(currency);
509 tvCurrency.setTextColor(Colors.defaultTextColor);
512 private void setCurrency(Currency currency) {
513 setCurrencyString((currency == null) ? null : currency.getName());
515 private void setEditable(Boolean editable) {
516 tvDate.setEnabled(editable);
517 tvDescription.setEnabled(editable);
518 tvAccount.setEnabled(editable);
519 tvAmount.setEnabled(editable);
521 private void beginUpdates() {
523 throw new RuntimeException("Already in update mode");
526 private void endUpdates() {
528 throw new RuntimeException("Not in update mode");
534 * Stores the data from the UI elements into the model item
535 * Returns true if there were changes made that suggest transaction has to be
536 * checked for being submittable
538 private boolean syncData() {
543 Logger.debug("new-trans", "skipping syncData() loop");
550 switch (item.getType()) {
552 item.setDate(String.valueOf(tvDate.getText()));
553 item.setDescription(String.valueOf(tvDescription.getText()));
554 item.setTransactionComment(String.valueOf(tvTransactionComment.getText()));
557 final LedgerTransactionAccount account = item.getAccount();
558 account.setAccountName(String.valueOf(tvAccount.getText()));
560 item.setComment(String.valueOf(tvComment.getText()));
562 String amount = String.valueOf(tvAmount.getText());
563 amount = amount.trim();
565 if (amount.isEmpty()) {
566 account.resetAmount();
567 item.validateAmount();
571 amount = amount.replace(decimalSeparator, decimalDot);
572 account.setAmount(Float.parseFloat(amount));
573 item.validateAmount();
575 catch (NumberFormatException e) {
576 Logger.debug("new-trans", String.format(
577 "assuming amount is not set due to number format exception. " +
578 "input was '%s'", amount));
579 account.invalidateAmount();
580 item.invalidateAmount();
582 final String curr = String.valueOf(tvCurrency.getText());
583 if (curr.equals(tvCurrency.getContext()
585 .getString(R.string.currency_symbol)) ||
587 account.setCurrency(null);
589 account.setCurrency(curr);
594 throw new RuntimeException("Should not happen");
603 private void pickTransactionDate() {
604 DatePickerFragment picker = new DatePickerFragment();
605 picker.setFutureDates(mProfile.getFutureDates());
606 picker.setOnDatePickedListener(this);
607 picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
613 * @param item updates the UI elements with the data from the model item
615 @SuppressLint("DefaultLocale")
616 public void setData(NewTransactionModel.Item item) {
619 if (this.item != null && !this.item.equals(item)) {
620 this.item.stopObservingDate(dateObserver);
621 this.item.stopObservingDescription(descriptionObserver);
622 this.item.stopObservingTransactionComment(transactionCommentObserver);
623 this.item.stopObservingAmountHint(hintObserver);
624 this.item.stopObservingEditableFlag(editableObserver);
626 .stopObservingFocusedItem(focusedAccountObserver);
628 .stopObservingAccountCount(accountCountObserver);
629 Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
630 Data.currencyGap.removeObserver(currencyGapObserver);
631 Data.locale.removeObserver(localeObserver);
632 this.item.stopObservingCurrency(currencyObserver);
633 this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
634 this.item.stopObservingComment(commentObserver);
635 this.item.getModel().showComments.removeObserver(showCommentsObserver);
636 this.item.stopObservingAmountValidity(amountValidityObserver);
641 switch (item.getType()) {
643 tvDate.setText(item.getFormattedDate());
644 tvDescription.setText(item.getDescription());
645 tvTransactionComment.setText(item.getTransactionComment());
646 lHead.setVisibility(View.VISIBLE);
647 lAccount.setVisibility(View.GONE);
648 lPadding.setVisibility(View.GONE);
652 LedgerTransactionAccount acc = item.getAccount();
653 tvAccount.setText(acc.getAccountName());
654 tvComment.setText(acc.getComment());
655 if (acc.isAmountSet()) {
656 tvAmount.setText(String.format("%1.2f", acc.getAmount()));
659 tvAmount.setText("");
660 // tvAmount.setHint(R.string.zero_amount);
662 tvAmount.setHint(item.getAmountHint());
663 setCurrencyString(acc.getCurrency());
664 lHead.setVisibility(View.GONE);
665 lAccount.setVisibility(View.VISIBLE);
666 lPadding.setVisibility(View.GONE);
670 lHead.setVisibility(View.GONE);
671 lAccount.setVisibility(View.GONE);
672 lPadding.setVisibility(View.VISIBLE);
676 if (this.item == null) { // was null or has changed
678 final NewTransactionActivity activity =
679 (NewTransactionActivity) tvDescription.getContext();
681 if (!item.isOfType(ItemType.bottomFiller)) {
682 item.observeEditableFlag(activity, editableObserver);
684 .observeFocusedItem(activity, focusedAccountObserver);
686 .observeShowComments(activity, showCommentsObserver);
688 switch (item.getType()) {
690 item.observeDate(activity, dateObserver);
691 item.observeDescription(activity, descriptionObserver);
692 item.observeTransactionComment(activity, transactionCommentObserver);
695 item.observeAmountHint(activity, hintObserver);
696 Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
697 Data.currencyGap.observe(activity, currencyGapObserver);
698 Data.locale.observe(activity, localeObserver);
699 item.observeCurrency(activity, currencyObserver);
700 item.getModel().showCurrency.observe(activity, showCurrencyObserver);
701 item.observeComment(activity, commentObserver);
703 .observeAccountCount(activity, accountCountObserver);
704 item.observeAmountValidity(activity, amountValidityObserver);
714 public void onDatePicked(int year, int month, int day) {
715 final Calendar c = GregorianCalendar.getInstance();
716 c.set(year, month, day);
717 item.setDate(c.getTime());
718 boolean focused = tvDescription.requestFocus();
720 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
724 public void descriptionSelected(String description) {
725 tvAccount.setText(description);
726 tvAmount.requestFocus(View.FOCUS_FORWARD);