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.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.NonNull;
34 import androidx.appcompat.app.AppCompatActivity;
35 import androidx.constraintlayout.widget.ConstraintLayout;
36 import androidx.lifecycle.Observer;
37 import androidx.recyclerview.widget.RecyclerView;
39 import net.ktnx.mobileledger.R;
40 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
41 import net.ktnx.mobileledger.model.Currency;
42 import net.ktnx.mobileledger.model.Data;
43 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
44 import net.ktnx.mobileledger.model.MobileLedgerProfile;
45 import net.ktnx.mobileledger.ui.CurrencySelectorFragment;
46 import net.ktnx.mobileledger.ui.DatePickerFragment;
47 import net.ktnx.mobileledger.ui.TextViewClearHelper;
48 import net.ktnx.mobileledger.utils.Colors;
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;
54 import java.text.DecimalFormatSymbols;
55 import java.util.Calendar;
56 import java.util.Date;
57 import java.util.GregorianCalendar;
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 AutoCompleteTextView tvAccount;
73 private TextView tvComment;
74 private EditText tvAmount;
75 private ViewGroup lHead;
76 private ViewGroup lAccount;
77 private FrameLayout lPadding;
78 private MobileLedgerProfile mProfile;
80 private Observer<Date> dateObserver;
81 private Observer<String> descriptionObserver;
82 private Observer<String> transactionCommentObserver;
83 private Observer<String> hintObserver;
84 private Observer<Integer> focusedAccountObserver;
85 private Observer<Integer> accountCountObserver;
86 private Observer<Boolean> editableObserver;
87 private Observer<Currency.Position> currencyPositionObserver;
88 private Observer<Boolean> currencyGapObserver;
89 private Observer<Locale> localeObserver;
90 private Observer<Currency> currencyObserver;
91 private Observer<Boolean> showCurrencyObserver;
92 private Observer<String> commentObserver;
93 private Observer<Boolean> amountValidityObserver;
94 private boolean inUpdate = false;
95 private boolean syncingData = false;
96 private View commentButton;
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 commentButton = lAccount.findViewById(R.id.comment_button);
106 tvAmount = itemView.findViewById(R.id.account_row_acc_amounts);
107 tvCurrency = itemView.findViewById(R.id.currency);
108 tvDate = itemView.findViewById(R.id.new_transaction_date);
109 tvDescription = itemView.findViewById(R.id.new_transaction_description);
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 commentButton.setOnClickListener(v -> {
123 tvComment.setVisibility(View.VISIBLE);
124 tvComment.requestFocus();
127 transactionCommentLayout.findViewById(R.id.comment_button)
128 .setOnClickListener(v -> {
129 tvTransactionComment.setVisibility(View.VISIBLE);
130 tvTransactionComment.requestFocus();
133 mProfile = Data.profile.getValue();
134 if (mProfile == null)
135 throw new AssertionError();
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(commentLayout, tvComment, hasFocus);
171 else if (id == R.id.transaction_comment) {
172 commentFocusChanged(transactionCommentLayout, 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 -> {
190 decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance(locale)
191 .getMonetaryDecimalSeparator());
196 final TextWatcher tw = new TextWatcher() {
198 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
202 public void onTextChanged(CharSequence s, int start, int before, int count) {
206 public void afterTextChanged(Editable s) {
207 // debug("input", "text changed");
211 Logger.debug("textWatcher", "calling syncData()");
213 Logger.debug("textWatcher",
214 "syncData() returned, checking if transaction is submittable");
215 adapter.checkTransactionSubmittable();
216 Logger.debug("textWatcher", "done");
219 final TextWatcher amountWatcher = new TextWatcher() {
221 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
223 String.format(Locale.US, "beforeTextChanged: start=%d, count=%d, after=%d",
224 start, count, after));
227 public void onTextChanged(CharSequence s, int start, int before, int count) {}
229 public void afterTextChanged(Editable s) {
232 adapter.checkTransactionSubmittable();
235 tvDescription.addTextChangedListener(tw);
236 tvTransactionComment.addTextChangedListener(tw);
237 tvAccount.addTextChangedListener(tw);
238 tvComment.addTextChangedListener(tw);
239 tvAmount.addTextChangedListener(amountWatcher);
241 tvCurrency.setOnClickListener(v -> {
242 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
243 cpf.showPositionAndPadding();
244 cpf.setOnCurrencySelectedListener(c -> item.setCurrency(c));
245 final AppCompatActivity activity = (AppCompatActivity) v.getContext();
246 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
249 dateObserver = date -> {
254 tvDate.setText(item.getFormattedDate());
260 descriptionObserver = description -> {
265 tvDescription.setText(description);
271 transactionCommentObserver = transactionComment -> {
272 final View focusedView = tvTransactionComment.findFocus();
273 tvTransactionComment.setTypeface(null,
274 (focusedView == tvTransactionComment) ? Typeface.NORMAL : Typeface.ITALIC);
275 tvTransactionComment.setVisibility(((focusedView != tvTransactionComment) &&
276 Misc.isEmptyOrNull(transactionComment))
277 ? View.INVISIBLE : View.VISIBLE);
280 hintObserver = hint -> {
286 tvAmount.setHint(R.string.zero_amount);
288 tvAmount.setHint(hint);
294 editableObserver = this::setEditable;
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(View layout, TextView textView, boolean hasFocus) {
436 textColor = Colors.defaultTextColor;
437 textView.setTypeface(null, Typeface.NORMAL);
438 textView.setHint(R.string.transaction_account_comment_hint);
441 textColor = Colors.defaultTextColorDisabled;
442 textView.setTypeface(null, Typeface.ITALIC);
443 textView.setHint("");
444 if (Misc.isEmptyOrNull(textView.getText())) {
445 textView.setVisibility(View.INVISIBLE);
448 textView.setTextColor(textColor);
451 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
452 ConstraintLayout.LayoutParams amountLP =
453 (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
454 ConstraintLayout.LayoutParams currencyLP =
455 (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
457 if (position == Currency.Position.before) {
458 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
459 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
461 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
462 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
463 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
464 amountLP.startToEnd = tvCurrency.getId();
466 tvCurrency.setGravity(Gravity.END);
469 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
470 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
472 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
473 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
474 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
475 amountLP.endToStart = tvCurrency.getId();
477 tvCurrency.setGravity(Gravity.START);
480 amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
481 currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
483 tvAmount.setLayoutParams(amountLP);
484 tvCurrency.setLayoutParams(currencyLP);
486 // distance between the amount and the currency symbol
487 int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
489 if (position == Currency.Position.before) {
490 tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
493 tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
496 private void setCurrencyString(String currency) {
497 if ((currency == null) || currency.isEmpty()) {
498 tvCurrency.setText(R.string.currency_symbol);
499 tvCurrency.setTextColor(0x7f000000 + (0x00ffffff & Colors.defaultTextColor));
502 tvCurrency.setText(currency);
503 tvCurrency.setTextColor(Colors.defaultTextColor);
506 private void setCurrency(Currency currency) {
507 setCurrencyString((currency == null) ? null : currency.getName());
509 private void setEditable(Boolean editable) {
510 tvDate.setEnabled(editable);
511 tvDescription.setEnabled(editable);
512 tvAccount.setEnabled(editable);
513 tvAmount.setEnabled(editable);
515 private void beginUpdates() {
517 throw new RuntimeException("Already in update mode");
520 private void endUpdates() {
522 throw new RuntimeException("Not in update mode");
528 * Stores the data from the UI elements into the model item
529 * Returns true if there were changes made that suggest transaction has to be
530 * checked for being submittable
532 private boolean syncData() {
537 Logger.debug("new-trans", "skipping syncData() loop");
544 switch (item.getType()) {
546 item.setDate(String.valueOf(tvDate.getText()));
547 item.setDescription(String.valueOf(tvDescription.getText()));
548 item.setTransactionComment(String.valueOf(tvTransactionComment.getText()));
551 final LedgerTransactionAccount account = item.getAccount();
552 account.setAccountName(String.valueOf(tvAccount.getText()));
554 item.setComment(String.valueOf(tvComment.getText()));
556 String amount = String.valueOf(tvAmount.getText());
557 amount = amount.trim();
559 if (amount.isEmpty()) {
560 account.resetAmount();
561 item.validateAmount();
565 amount = amount.replace(decimalSeparator, decimalDot);
566 account.setAmount(Float.parseFloat(amount));
567 item.validateAmount();
569 catch (NumberFormatException e) {
570 Logger.debug("new-trans", String.format(
571 "assuming amount is not set due to number format exception. " +
572 "input was '%s'", amount));
573 account.invalidateAmount();
574 item.invalidateAmount();
576 final String curr = String.valueOf(tvCurrency.getText());
577 if (curr.equals(tvCurrency.getContext()
579 .getString(R.string.currency_symbol)) ||
581 account.setCurrency(null);
583 account.setCurrency(curr);
588 throw new RuntimeException("Should not happen");
597 private void pickTransactionDate() {
598 DatePickerFragment picker = new DatePickerFragment();
599 picker.setFutureDates(mProfile.getFutureDates());
600 picker.setOnDatePickedListener(this);
601 picker.setCurrentDateFromText(tvDate.getText());
602 picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
608 * @param item updates the UI elements with the data from the model item
610 @SuppressLint("DefaultLocale")
611 public void setData(NewTransactionModel.Item item) {
614 if (this.item != null && !this.item.equals(item)) {
615 this.item.stopObservingDate(dateObserver);
616 this.item.stopObservingDescription(descriptionObserver);
617 this.item.stopObservingTransactionComment(transactionCommentObserver);
618 this.item.stopObservingAmountHint(hintObserver);
619 this.item.stopObservingEditableFlag(editableObserver);
621 .stopObservingFocusedItem(focusedAccountObserver);
623 .stopObservingAccountCount(accountCountObserver);
624 Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
625 Data.currencyGap.removeObserver(currencyGapObserver);
626 Data.locale.removeObserver(localeObserver);
627 this.item.stopObservingCurrency(currencyObserver);
628 this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
629 this.item.stopObservingComment(commentObserver);
630 this.item.getModel().showComments.removeObserver(showCommentsObserver);
631 this.item.stopObservingAmountValidity(amountValidityObserver);
636 switch (item.getType()) {
638 tvDate.setText(item.getFormattedDate());
639 tvDescription.setText(item.getDescription());
640 tvTransactionComment.setText(item.getTransactionComment());
641 lHead.setVisibility(View.VISIBLE);
642 lAccount.setVisibility(View.GONE);
643 lPadding.setVisibility(View.GONE);
647 LedgerTransactionAccount acc = item.getAccount();
648 tvAccount.setText(acc.getAccountName());
649 tvComment.setText(acc.getComment());
650 if (acc.isAmountSet()) {
651 tvAmount.setText(String.format("%1.2f", acc.getAmount()));
654 tvAmount.setText("");
655 // tvAmount.setHint(R.string.zero_amount);
657 tvAmount.setHint(item.getAmountHint());
658 setCurrencyString(acc.getCurrency());
659 lHead.setVisibility(View.GONE);
660 lAccount.setVisibility(View.VISIBLE);
661 lPadding.setVisibility(View.GONE);
665 lHead.setVisibility(View.GONE);
666 lAccount.setVisibility(View.GONE);
667 lPadding.setVisibility(View.VISIBLE);
671 if (this.item == null) { // was null or has changed
673 final NewTransactionActivity activity =
674 (NewTransactionActivity) tvDescription.getContext();
676 if (!item.isOfType(ItemType.bottomFiller)) {
677 item.observeEditableFlag(activity, editableObserver);
679 .observeFocusedItem(activity, focusedAccountObserver);
681 .observeShowComments(activity, showCommentsObserver);
683 switch (item.getType()) {
685 item.observeDate(activity, dateObserver);
686 item.observeDescription(activity, descriptionObserver);
687 item.observeTransactionComment(activity, transactionCommentObserver);
690 item.observeAmountHint(activity, hintObserver);
691 Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
692 Data.currencyGap.observe(activity, currencyGapObserver);
693 Data.locale.observe(activity, localeObserver);
694 item.observeCurrency(activity, currencyObserver);
695 item.getModel().showCurrency.observe(activity, showCurrencyObserver);
696 item.observeComment(activity, commentObserver);
698 .observeAccountCount(activity, accountCountObserver);
699 item.observeAmountValidity(activity, amountValidityObserver);
709 public void onDatePicked(int year, int month, int day) {
710 final Calendar c = GregorianCalendar.getInstance();
711 c.set(year, month, day);
712 item.setDate(c.getTime());
713 boolean focused = tvDescription.requestFocus();
715 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
719 public void descriptionSelected(String description) {
720 tvAccount.setText(description);
721 tvAmount.requestFocus(View.FOCUS_FORWARD);