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 decimalSeparator;
67 private final String decimalDot;
68 private final TextView tvCurrency;
69 private final Observer<Boolean> showCommentsObserver;
70 private final TextView tvTransactionComment;
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 // FIXME: react on configuration (locale) changes
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 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
248 tvAmount.setKeyListener(
249 DigitsKeyListener.getInstance(Data.locale.getValue(), true, true));
251 tvAmount.setKeyListener(
252 DigitsKeyListener.getInstance("0123456789+-" + decimalSeparator + decimalDot));
254 dateObserver = date -> {
259 tvDate.setText(item.getFormattedDate());
265 descriptionObserver = description -> {
270 tvDescription.setText(description);
276 transactionCommentObserver = transactionComment -> {
277 final View focusedView = tvTransactionComment.findFocus();
278 tvTransactionComment.setTypeface(null,
279 (focusedView == tvTransactionComment) ? Typeface.NORMAL : Typeface.ITALIC);
280 tvTransactionComment.setVisibility(((focusedView != tvTransactionComment) &&
281 Misc.isEmptyOrNull(transactionComment))
282 ? View.INVISIBLE : View.VISIBLE);
285 hintObserver = hint -> {
291 tvAmount.setHint(R.string.zero_amount);
293 tvAmount.setHint(hint);
299 editableObserver = this::setEditable;
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 localeObserver = locale -> {
371 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
372 tvAmount.setKeyListener(DigitsKeyListener.getInstance(locale, true, true));
375 currencyObserver = currency -> {
376 setCurrency(currency);
377 adapter.checkTransactionSubmittable();
380 currencyGapObserver =
381 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
384 currencyPositionObserver =
385 position -> updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
387 showCurrencyObserver = showCurrency -> {
389 tvCurrency.setVisibility(View.VISIBLE);
392 tvCurrency.setVisibility(View.GONE);
393 item.setCurrency(null);
397 commentObserver = comment -> {
398 final View focusedView = tvComment.findFocus();
399 tvComment.setTypeface(null,
400 (focusedView == tvComment) ? Typeface.NORMAL : Typeface.ITALIC);
401 tvComment.setVisibility(
402 ((focusedView != tvComment) && Misc.isEmptyOrNull(comment)) ? View.INVISIBLE
406 showCommentsObserver = show -> {
407 final View amountLayout = itemView.findViewById(R.id.amount_layout);
408 ConstraintLayout.LayoutParams amountLayoutParams =
409 (ConstraintLayout.LayoutParams) amountLayout.getLayoutParams();
410 ConstraintLayout.LayoutParams accountParams =
411 (ConstraintLayout.LayoutParams) tvAccount.getLayoutParams();
413 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
414 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
416 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
417 amountLayoutParams.topToBottom = tvAccount.getId();
419 commentLayout.setVisibility(View.VISIBLE);
422 accountParams.endToStart = amountLayout.getId();
423 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
425 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
426 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
428 commentLayout.setVisibility(View.GONE);
431 tvAccount.setLayoutParams(accountParams);
432 amountLayout.setLayoutParams(amountLayoutParams);
434 transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
437 amountValidityObserver = valid -> {
438 tvAmount.setCompoundDrawablesRelativeWithIntrinsicBounds(
439 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
440 tvAmount.setMinEms(valid ? 4 : 5);
443 private void commentFocusChanged(View layout, TextView textView, boolean hasFocus) {
446 textColor = Colors.defaultTextColor;
447 textView.setTypeface(null, Typeface.NORMAL);
448 textView.setHint(R.string.transaction_account_comment_hint);
451 textColor = Colors.defaultTextColorDisabled;
452 textView.setTypeface(null, Typeface.ITALIC);
453 textView.setHint("");
454 if (Misc.isEmptyOrNull(textView.getText())) {
455 textView.setVisibility(View.INVISIBLE);
458 textView.setTextColor(textColor);
461 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
462 ConstraintLayout.LayoutParams amountLP =
463 (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
464 ConstraintLayout.LayoutParams currencyLP =
465 (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
467 if (position == Currency.Position.before) {
468 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
469 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
471 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
472 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
473 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
474 amountLP.startToEnd = tvCurrency.getId();
476 tvCurrency.setGravity(Gravity.END);
479 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
480 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
482 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
483 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
484 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
485 amountLP.endToStart = tvCurrency.getId();
487 tvCurrency.setGravity(Gravity.START);
490 amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
491 currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
493 tvAmount.setLayoutParams(amountLP);
494 tvCurrency.setLayoutParams(currencyLP);
496 // distance between the amount and the currency symbol
497 int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
499 if (position == Currency.Position.before) {
500 tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
503 tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
506 private void setCurrencyString(String currency) {
507 if ((currency == null) || currency.isEmpty()) {
508 tvCurrency.setText(R.string.currency_symbol);
509 tvCurrency.setTextColor(0x7f000000 + (0x00ffffff & Colors.defaultTextColor));
512 tvCurrency.setText(currency);
513 tvCurrency.setTextColor(Colors.defaultTextColor);
516 private void setCurrency(Currency currency) {
517 setCurrencyString((currency == null) ? null : currency.getName());
519 private void setEditable(Boolean editable) {
520 tvDate.setEnabled(editable);
521 tvDescription.setEnabled(editable);
522 tvAccount.setEnabled(editable);
523 tvAmount.setEnabled(editable);
525 private void beginUpdates() {
527 throw new RuntimeException("Already in update mode");
530 private void endUpdates() {
532 throw new RuntimeException("Not in update mode");
538 * Stores the data from the UI elements into the model item
539 * Returns true if there were changes made that suggest transaction has to be
540 * checked for being submittable
542 private boolean syncData() {
547 Logger.debug("new-trans", "skipping syncData() loop");
554 switch (item.getType()) {
556 item.setDate(String.valueOf(tvDate.getText()));
557 item.setDescription(String.valueOf(tvDescription.getText()));
558 item.setTransactionComment(String.valueOf(tvTransactionComment.getText()));
561 final LedgerTransactionAccount account = item.getAccount();
562 account.setAccountName(String.valueOf(tvAccount.getText()));
564 item.setComment(String.valueOf(tvComment.getText()));
566 String amount = String.valueOf(tvAmount.getText());
567 amount = amount.trim();
569 if (amount.isEmpty()) {
570 account.resetAmount();
571 item.validateAmount();
575 amount = amount.replace(decimalSeparator, decimalDot);
576 account.setAmount(Float.parseFloat(amount));
577 item.validateAmount();
579 catch (NumberFormatException e) {
580 Logger.debug("new-trans", String.format(
581 "assuming amount is not set due to number format exception. " +
582 "input was '%s'", amount));
583 account.invalidateAmount();
584 item.invalidateAmount();
586 final String curr = String.valueOf(tvCurrency.getText());
587 if (curr.equals(tvCurrency.getContext()
589 .getString(R.string.currency_symbol)) ||
591 account.setCurrency(null);
593 account.setCurrency(curr);
598 throw new RuntimeException("Should not happen");
607 private void pickTransactionDate() {
608 DatePickerFragment picker = new DatePickerFragment();
609 picker.setFutureDates(mProfile.getFutureDates());
610 picker.setOnDatePickedListener(this);
611 picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
617 * @param item updates the UI elements with the data from the model item
619 @SuppressLint("DefaultLocale")
620 public void setData(NewTransactionModel.Item item) {
623 if (this.item != null && !this.item.equals(item)) {
624 this.item.stopObservingDate(dateObserver);
625 this.item.stopObservingDescription(descriptionObserver);
626 this.item.stopObservingTransactionComment(transactionCommentObserver);
627 this.item.stopObservingAmountHint(hintObserver);
628 this.item.stopObservingEditableFlag(editableObserver);
630 .stopObservingFocusedItem(focusedAccountObserver);
632 .stopObservingAccountCount(accountCountObserver);
633 Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
634 Data.currencyGap.removeObserver(currencyGapObserver);
635 Data.locale.removeObserver(localeObserver);
636 this.item.stopObservingCurrency(currencyObserver);
637 this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
638 this.item.stopObservingComment(commentObserver);
639 this.item.getModel().showComments.removeObserver(showCommentsObserver);
640 this.item.stopObservingAmountValidity(amountValidityObserver);
645 switch (item.getType()) {
647 tvDate.setText(item.getFormattedDate());
648 tvDescription.setText(item.getDescription());
649 tvTransactionComment.setText(item.getTransactionComment());
650 lHead.setVisibility(View.VISIBLE);
651 lAccount.setVisibility(View.GONE);
652 lPadding.setVisibility(View.GONE);
656 LedgerTransactionAccount acc = item.getAccount();
657 tvAccount.setText(acc.getAccountName());
658 tvComment.setText(acc.getComment());
659 if (acc.isAmountSet()) {
660 tvAmount.setText(String.format("%1.2f", acc.getAmount()));
663 tvAmount.setText("");
664 // tvAmount.setHint(R.string.zero_amount);
666 tvAmount.setHint(item.getAmountHint());
667 setCurrencyString(acc.getCurrency());
668 lHead.setVisibility(View.GONE);
669 lAccount.setVisibility(View.VISIBLE);
670 lPadding.setVisibility(View.GONE);
674 lHead.setVisibility(View.GONE);
675 lAccount.setVisibility(View.GONE);
676 lPadding.setVisibility(View.VISIBLE);
680 if (this.item == null) { // was null or has changed
682 final NewTransactionActivity activity =
683 (NewTransactionActivity) tvDescription.getContext();
685 if (!item.isOfType(ItemType.bottomFiller)) {
686 item.observeEditableFlag(activity, editableObserver);
688 .observeFocusedItem(activity, focusedAccountObserver);
690 .observeShowComments(activity, showCommentsObserver);
692 switch (item.getType()) {
694 item.observeDate(activity, dateObserver);
695 item.observeDescription(activity, descriptionObserver);
696 item.observeTransactionComment(activity, transactionCommentObserver);
699 item.observeAmountHint(activity, hintObserver);
700 Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
701 Data.currencyGap.observe(activity, currencyGapObserver);
702 Data.locale.observe(activity, localeObserver);
703 item.observeCurrency(activity, currencyObserver);
704 item.getModel().showCurrency.observe(activity, showCurrencyObserver);
705 item.observeComment(activity, commentObserver);
707 .observeAccountCount(activity, accountCountObserver);
708 item.observeAmountValidity(activity, amountValidityObserver);
718 public void onDatePicked(int year, int month, int day) {
719 final Calendar c = GregorianCalendar.getInstance();
720 c.set(year, month, day);
721 item.setDate(c.getTime());
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);