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 boolean inUpdate = false;
96 private boolean syncingData = false;
97 private View commentButton;
98 //TODO multiple amounts with different currencies per posting
99 NewTransactionItemHolder(@NonNull View itemView, NewTransactionItemsAdapter adapter) {
101 lAccount = itemView.findViewById(R.id.ntr_account);
102 tvAccount = lAccount.findViewById(R.id.account_row_acc_name);
103 tvComment = lAccount.findViewById(R.id.comment);
104 tvTransactionComment = itemView.findViewById(R.id.transaction_comment);
105 new TextViewClearHelper().attachToTextView((EditText) tvComment);
106 commentButton = lAccount.findViewById(R.id.comment_button);
107 tvAmount = itemView.findViewById(R.id.account_row_acc_amounts);
108 tvCurrency = itemView.findViewById(R.id.currency);
109 tvDate = itemView.findViewById(R.id.new_transaction_date);
110 tvDescription = itemView.findViewById(R.id.new_transaction_description);
111 lHead = itemView.findViewById(R.id.ntr_data);
112 lPadding = itemView.findViewById(R.id.ntr_padding);
113 final View commentLayout = itemView.findViewById(R.id.comment_layout);
114 final View transactionCommentLayout =
115 itemView.findViewById(R.id.transaction_comment_layout);
117 tvDescription.setNextFocusForwardId(View.NO_ID);
118 tvAccount.setNextFocusForwardId(View.NO_ID);
119 tvAmount.setNextFocusForwardId(View.NO_ID); // magic!
121 tvDate.setOnClickListener(v -> pickTransactionDate());
123 commentButton.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.profile.getValue();
135 if (mProfile == null)
136 throw new AssertionError();
138 View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
139 final int id = v.getId();
141 boolean wasSyncing = syncingData;
144 final int pos = getAdapterPosition();
145 adapter.updateFocusedItem(pos);
147 case R.id.account_row_acc_name:
148 adapter.noteFocusIsOnAccount(pos);
150 case R.id.account_row_acc_amounts:
151 adapter.noteFocusIsOnAmount(pos);
154 adapter.noteFocusIsOnComment(pos);
156 case R.id.transaction_comment:
157 adapter.noteFocusIsOnTransactionComment(pos);
159 case R.id.new_transaction_description:
160 adapter.noteFocusIsOnDescription(pos);
165 syncingData = wasSyncing;
169 if (id == R.id.comment) {
170 commentFocusChanged(commentLayout, tvComment, hasFocus);
172 else if ( id == R.id.transaction_comment) {
173 commentFocusChanged(transactionCommentLayout, tvTransactionComment, hasFocus);
177 tvDescription.setOnFocusChangeListener(focusMonitor);
178 tvAccount.setOnFocusChangeListener(focusMonitor);
179 tvAmount.setOnFocusChangeListener(focusMonitor);
180 tvComment.setOnFocusChangeListener(focusMonitor);
181 tvTransactionComment.setOnFocusChangeListener(focusMonitor);
183 MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
184 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
185 MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
186 "name", true, this, mProfile);
188 // FIXME: react on configuration (locale) changes
189 decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
190 .getMonetaryDecimalSeparator());
193 final TextWatcher tw = new TextWatcher() {
195 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
199 public void onTextChanged(CharSequence s, int start, int before, int count) {
203 public void afterTextChanged(Editable s) {
204 // debug("input", "text changed");
208 Logger.debug("textWatcher", "calling syncData()");
210 Logger.debug("textWatcher",
211 "syncData() returned, checking if transaction is submittable");
212 adapter.checkTransactionSubmittable();
213 Logger.debug("textWatcher", "done");
216 final TextWatcher amountWatcher = new TextWatcher() {
218 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
220 String.format(Locale.US, "beforeTextChanged: start=%d, count=%d, after=%d",
221 start, count, after));
224 public void onTextChanged(CharSequence s, int start, int before, int count) {}
226 public void afterTextChanged(Editable s) {
227 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
228 // only one decimal separator is allowed
229 // plus and minus are allowed only at the beginning
230 String allowed = "0123456789";
231 String val = s.toString();
232 Logger.debug("input", val);
233 if (val.isEmpty() || (tvAmount.getSelectionStart() == 0))
235 if (!val.contains(decimalSeparator) && !val.contains(decimalDot))
236 allowed += decimalSeparator + decimalDot;
238 tvAmount.setKeyListener(DigitsKeyListener.getInstance(allowed));
242 adapter.checkTransactionSubmittable();
245 tvDescription.addTextChangedListener(tw);
246 tvTransactionComment.addTextChangedListener(tw);
247 tvAccount.addTextChangedListener(tw);
248 tvComment.addTextChangedListener(tw);
249 tvAmount.addTextChangedListener(amountWatcher);
251 tvCurrency.setOnClickListener(v -> {
252 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
253 cpf.showPositionAndPadding();
254 cpf.setOnCurrencySelectedListener(c -> item.setCurrency(c));
255 final AppCompatActivity activity = (AppCompatActivity) v.getContext();
256 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
259 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
260 tvAmount.setKeyListener(
261 DigitsKeyListener.getInstance(Data.locale.getValue(), true, true));
263 tvAmount.setKeyListener(
264 DigitsKeyListener.getInstance("0123456789+-" + decimalSeparator + decimalDot));
266 dateObserver = date -> {
271 tvDate.setText(item.getFormattedDate());
277 descriptionObserver = description -> {
282 tvDescription.setText(description);
288 transactionCommentObserver = transactionComment -> {
289 final View focusedView = tvTransactionComment.findFocus();
290 tvTransactionComment.setTypeface(null,
291 (focusedView == tvTransactionComment) ? Typeface.NORMAL : Typeface.ITALIC);
292 tvTransactionComment.setVisibility(((focusedView != tvTransactionComment) &&
293 Misc.isEmptyOrNull(transactionComment))
294 ? View.INVISIBLE : View.VISIBLE);
297 hintObserver = hint -> {
303 tvAmount.setHint(R.string.zero_amount);
305 tvAmount.setHint(hint);
311 editableObserver = this::setEditable;
312 focusedAccountObserver = index -> {
313 if ((index == null) || !index.equals(getAdapterPosition()) || itemView.hasFocus())
316 switch (item.getType()) {
318 // bad idea - double pop-up, and not really necessary.
319 // the user can tap the input to get the calendar
320 //if (!tvDate.hasFocus()) tvDate.requestFocus();
321 switch (item.getFocusedElement()) {
322 case TransactionComment:
323 tvTransactionComment.setVisibility(View.VISIBLE);
324 tvTransactionComment.requestFocus();
327 boolean focused = tvDescription.requestFocus();
328 tvDescription.dismissDropDown();
330 Misc.showSoftKeyboard(
331 (NewTransactionActivity) tvDescription.getContext());
336 switch (item.getFocusedElement()) {
338 tvAmount.requestFocus();
341 tvComment.setVisibility(View.VISIBLE);
342 tvComment.requestFocus();
345 boolean focused = tvAccount.requestFocus();
346 tvAccount.dismissDropDown();
348 Misc.showSoftKeyboard(
349 (NewTransactionActivity) tvAccount.getContext());
356 accountCountObserver = count -> {
357 final int adapterPosition = getAdapterPosition();
358 final int layoutPosition = getLayoutPosition();
359 Logger.debug("holder",
360 String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
361 adapterPosition, layoutPosition, item.getType()
363 .concat(item.getType() ==
364 ItemType.transactionRow
365 ? String.format(Locale.US,
371 ? String.format(Locale.US,
376 if (adapterPosition == count)
377 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
379 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
382 localeObserver = locale -> {
383 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
384 tvAmount.setKeyListener(DigitsKeyListener.getInstance(locale, true, true));
387 currencyObserver = currency -> {
388 setCurrency(currency);
389 adapter.checkTransactionSubmittable();
392 currencyGapObserver =
393 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
396 currencyPositionObserver =
397 position -> updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
399 showCurrencyObserver = showCurrency -> {
401 tvCurrency.setVisibility(View.VISIBLE);
404 tvCurrency.setVisibility(View.GONE);
405 item.setCurrency(null);
409 commentObserver = comment -> {
410 final View focusedView = tvComment.findFocus();
411 tvComment.setTypeface(null,
412 (focusedView == tvComment) ? Typeface.NORMAL : Typeface.ITALIC);
413 tvComment.setVisibility(
414 ((focusedView != tvComment) && Misc.isEmptyOrNull(comment)) ? View.INVISIBLE
418 showCommentsObserver = show -> {
419 final View amountLayout = itemView.findViewById(R.id.amount_layout);
420 ConstraintLayout.LayoutParams amountLayoutParams =
421 (ConstraintLayout.LayoutParams) amountLayout.getLayoutParams();
422 ConstraintLayout.LayoutParams accountParams =
423 (ConstraintLayout.LayoutParams) tvAccount.getLayoutParams();
425 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
426 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
428 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
429 amountLayoutParams.topToBottom = tvAccount.getId();
431 commentLayout.setVisibility(View.VISIBLE);
434 accountParams.endToStart = amountLayout.getId();
435 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
437 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
438 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
440 commentLayout.setVisibility(View.GONE);
443 tvAccount.setLayoutParams(accountParams);
444 amountLayout.setLayoutParams(amountLayoutParams);
446 transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
449 private void commentFocusChanged(View layout, TextView textView, boolean hasFocus) {
452 textColor = Colors.defaultTextColor;
453 textView.setTypeface(null, Typeface.NORMAL);
454 textView.setHint(R.string.transaction_account_comment_hint);
457 textColor = Colors.defaultTextColorDisabled;
458 textView.setTypeface(null, Typeface.ITALIC);
459 textView.setHint("");
460 if (Misc.isEmptyOrNull(textView.getText())) {
461 textView.setVisibility(View.INVISIBLE);
464 textView.setTextColor(textColor);
467 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
468 ConstraintLayout.LayoutParams amountLP =
469 (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
470 ConstraintLayout.LayoutParams currencyLP =
471 (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
473 if (position == Currency.Position.before) {
474 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
475 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
477 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
478 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
479 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
480 amountLP.startToEnd = tvCurrency.getId();
482 tvCurrency.setGravity(Gravity.END);
485 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
486 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
488 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
489 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
490 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
491 amountLP.endToStart = tvCurrency.getId();
493 tvCurrency.setGravity(Gravity.START);
496 amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
497 currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
499 tvAmount.setLayoutParams(amountLP);
500 tvCurrency.setLayoutParams(currencyLP);
502 // distance between the amount and the currency symbol
503 int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
505 if (position == Currency.Position.before) {
506 tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
509 tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
512 private void setCurrencyString(String currency) {
513 if ((currency == null) || currency.isEmpty()) {
514 tvCurrency.setText(R.string.currency_symbol);
515 tvCurrency.setTextColor(0x7f000000 + (0x00ffffff & Colors.defaultTextColor));
518 tvCurrency.setText(currency);
519 tvCurrency.setTextColor(Colors.defaultTextColor);
522 private void setCurrency(Currency currency) {
523 setCurrencyString((currency == null) ? null : currency.getName());
525 private void setEditable(Boolean editable) {
526 tvDate.setEnabled(editable);
527 tvDescription.setEnabled(editable);
528 tvAccount.setEnabled(editable);
529 tvAmount.setEnabled(editable);
531 private void beginUpdates() {
533 throw new RuntimeException("Already in update mode");
536 private void endUpdates() {
538 throw new RuntimeException("Not in update mode");
544 * Stores the data from the UI elements into the model item
545 * Returns true if there were changes made that suggest transaction has to be
546 * checked for being submittable
548 private boolean syncData() {
553 Logger.debug("new-trans", "skipping syncData() loop");
560 switch (item.getType()) {
562 item.setDate(String.valueOf(tvDate.getText()));
563 item.setDescription(String.valueOf(tvDescription.getText()));
564 item.setTransactionComment(String.valueOf(tvTransactionComment.getText()));
567 final LedgerTransactionAccount account = item.getAccount();
568 account.setAccountName(String.valueOf(tvAccount.getText()));
570 item.setComment(String.valueOf(tvComment.getText()));
572 String amount = String.valueOf(tvAmount.getText());
573 amount = amount.trim();
575 if (amount.isEmpty()) {
576 account.resetAmount();
577 // account.setCurrency(null);
581 amount = amount.replace(decimalSeparator, decimalDot);
582 account.setAmount(Float.parseFloat(amount));
584 catch (NumberFormatException e) {
585 Logger.debug("new-trans", String.format(
586 "assuming amount is not set due to number format exception. " +
587 "input was '%s'", amount));
588 account.resetAmount();
590 final String curr = String.valueOf(tvCurrency.getText());
591 if (curr.equals(tvCurrency.getContext()
593 .getString(R.string.currency_symbol)) ||
595 account.setCurrency(null);
597 account.setCurrency(curr);
602 throw new RuntimeException("Should not happen");
611 private void pickTransactionDate() {
612 DatePickerFragment picker = new DatePickerFragment();
613 picker.setFutureDates(mProfile.getFutureDates());
614 picker.setOnDatePickedListener(this);
615 picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
621 * @param item updates the UI elements with the data from the model item
623 @SuppressLint("DefaultLocale")
624 public void setData(NewTransactionModel.Item item) {
627 if (this.item != null && !this.item.equals(item)) {
628 this.item.stopObservingDate(dateObserver);
629 this.item.stopObservingDescription(descriptionObserver);
630 this.item.stopObservingTransactionComment(transactionCommentObserver);
631 this.item.stopObservingAmountHint(hintObserver);
632 this.item.stopObservingEditableFlag(editableObserver);
634 .stopObservingFocusedItem(focusedAccountObserver);
636 .stopObservingAccountCount(accountCountObserver);
637 Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
638 Data.currencyGap.removeObserver(currencyGapObserver);
639 Data.locale.removeObserver(localeObserver);
640 this.item.stopObservingCurrency(currencyObserver);
641 this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
642 this.item.stopObservingComment(commentObserver);
643 this.item.getModel().showComments.removeObserver(showCommentsObserver);
648 switch (item.getType()) {
650 tvDate.setText(item.getFormattedDate());
651 tvDescription.setText(item.getDescription());
652 tvTransactionComment.setText(item.getTransactionComment());
653 lHead.setVisibility(View.VISIBLE);
654 lAccount.setVisibility(View.GONE);
655 lPadding.setVisibility(View.GONE);
659 LedgerTransactionAccount acc = item.getAccount();
660 tvAccount.setText(acc.getAccountName());
661 tvComment.setText(acc.getComment());
662 if (acc.isAmountSet()) {
663 tvAmount.setText(String.format("%1.2f", acc.getAmount()));
666 tvAmount.setText("");
667 // tvAmount.setHint(R.string.zero_amount);
669 tvAmount.setHint(item.getAmountHint());
670 setCurrencyString(acc.getCurrency());
671 lHead.setVisibility(View.GONE);
672 lAccount.setVisibility(View.VISIBLE);
673 lPadding.setVisibility(View.GONE);
677 lHead.setVisibility(View.GONE);
678 lAccount.setVisibility(View.GONE);
679 lPadding.setVisibility(View.VISIBLE);
683 if (this.item == null) { // was null or has changed
685 final NewTransactionActivity activity =
686 (NewTransactionActivity) tvDescription.getContext();
688 if (!item.isOfType(ItemType.bottomFiller)) {
689 item.observeEditableFlag(activity, editableObserver);
691 .observeFocusedItem(activity, focusedAccountObserver);
693 .observeShowComments(activity, showCommentsObserver);
695 switch (item.getType()) {
697 item.observeDate(activity, dateObserver);
698 item.observeDescription(activity, descriptionObserver);
699 item.observeTransactionComment(activity, transactionCommentObserver);
702 item.observeAmountHint(activity, hintObserver);
703 Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
704 Data.currencyGap.observe(activity, currencyGapObserver);
705 Data.locale.observe(activity, localeObserver);
706 item.observeCurrency(activity, currencyObserver);
707 item.getModel().showCurrency.observe(activity, showCurrencyObserver);
708 item.observeComment(activity, commentObserver);
710 .observeAccountCount(activity, accountCountObserver);
720 public void onDatePicked(int year, int month, int day) {
721 final Calendar c = GregorianCalendar.getInstance();
722 c.set(year, month, day);
723 item.setDate(c.getTime());
724 boolean focused = tvDescription.requestFocus();
726 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
730 public void descriptionSelected(String description) {
731 tvAccount.setText(description);
732 tvAmount.requestFocus(View.FOCUS_FORWARD);