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> hintObserver;
85 private Observer<Integer> focusedAccountObserver;
86 private Observer<Integer> accountCountObserver;
87 private Observer<Boolean> editableObserver;
88 private Observer<Currency.Position> currencyPositionObserver;
89 private Observer<Boolean> currencyGapObserver;
90 private Observer<Locale> localeObserver;
91 private Observer<Currency> currencyObserver;
92 private Observer<Boolean> showCurrencyObserver;
93 private Observer<String> commentObserver;
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 tvAccount = itemView.findViewById(R.id.account_row_acc_name);
101 tvComment = itemView.findViewById(R.id.comment);
102 tvTransactionComment = itemView.findViewById(R.id.transaction_comment);
103 new TextViewClearHelper().attachToTextView((EditText) tvComment);
104 commentButton = itemView.findViewById(R.id.comment_button);
105 tvAmount = itemView.findViewById(R.id.account_row_acc_amounts);
106 tvCurrency = itemView.findViewById(R.id.currency);
107 tvDate = itemView.findViewById(R.id.new_transaction_date);
108 tvDescription = itemView.findViewById(R.id.new_transaction_description);
109 lHead = itemView.findViewById(R.id.ntr_data);
110 lAccount = itemView.findViewById(R.id.ntr_account);
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 itemView.findViewById(R.id.transaction_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);
158 syncingData = wasSyncing;
162 if (id == R.id.comment) {
163 commentFocusChanged(commentLayout, tvComment, hasFocus);
165 else if ( id == R.id.transaction_comment) {
166 commentFocusChanged(transactionCommentLayout, tvTransactionComment, hasFocus);
170 tvDescription.setOnFocusChangeListener(focusMonitor);
171 tvAccount.setOnFocusChangeListener(focusMonitor);
172 tvAmount.setOnFocusChangeListener(focusMonitor);
173 tvComment.setOnFocusChangeListener(focusMonitor);
175 MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
176 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
177 MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
178 "name", true, this, mProfile);
180 // FIXME: react on configuration (locale) changes
181 decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
182 .getMonetaryDecimalSeparator());
185 final TextWatcher tw = new TextWatcher() {
187 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
191 public void onTextChanged(CharSequence s, int start, int before, int count) {
195 public void afterTextChanged(Editable s) {
196 // debug("input", "text changed");
200 Logger.debug("textWatcher", "calling syncData()");
202 Logger.debug("textWatcher",
203 "syncData() returned, checking if transaction is submittable");
204 adapter.checkTransactionSubmittable();
205 Logger.debug("textWatcher", "done");
208 final TextWatcher amountWatcher = new TextWatcher() {
210 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
212 String.format(Locale.US, "beforeTextChanged: start=%d, count=%d, after=%d",
213 start, count, after));
216 public void onTextChanged(CharSequence s, int start, int before, int count) {}
218 public void afterTextChanged(Editable s) {
219 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
220 // only one decimal separator is allowed
221 // plus and minus are allowed only at the beginning
222 String allowed = "0123456789";
223 String val = s.toString();
224 Logger.debug("input", val);
225 if (val.isEmpty() || (tvAmount.getSelectionStart() == 0))
227 if (!val.contains(decimalSeparator) && !val.contains(decimalDot))
228 allowed += decimalSeparator + decimalDot;
230 tvAmount.setKeyListener(DigitsKeyListener.getInstance(allowed));
234 adapter.checkTransactionSubmittable();
237 tvDescription.addTextChangedListener(tw);
238 tvAccount.addTextChangedListener(tw);
239 tvComment.addTextChangedListener(tw);
240 tvAmount.addTextChangedListener(amountWatcher);
242 tvCurrency.setOnClickListener(v -> {
243 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
244 cpf.showPositionAndPadding();
245 cpf.setOnCurrencySelectedListener(c -> item.setCurrency(c));
246 final AppCompatActivity activity = (AppCompatActivity) v.getContext();
247 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
250 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
251 tvAmount.setKeyListener(
252 DigitsKeyListener.getInstance(Data.locale.getValue(), true, true));
254 tvAmount.setKeyListener(
255 DigitsKeyListener.getInstance("0123456789+-" + decimalSeparator + decimalDot));
257 dateObserver = date -> {
262 tvDate.setText(item.getFormattedDate());
268 descriptionObserver = description -> {
273 tvDescription.setText(description);
279 hintObserver = hint -> {
285 tvAmount.setHint(R.string.zero_amount);
287 tvAmount.setHint(hint);
293 editableObserver = this::setEditable;
294 focusedAccountObserver = index -> {
295 if ((index != null) && index.equals(getAdapterPosition())) {
296 switch (item.getType()) {
298 // bad idea - double pop-up, and not really necessary.
299 // the user can tap the input to get the calendar
300 //if (!tvDate.hasFocus()) tvDate.requestFocus();
301 boolean focused = tvDescription.requestFocus();
302 tvDescription.dismissDropDown();
304 Misc.showSoftKeyboard(
305 (NewTransactionActivity) tvDescription.getContext());
308 // do nothing if a row element already has the focus
309 if (!itemView.hasFocus()) {
310 switch (item.getFocusedElement()) {
312 tvAmount.requestFocus();
315 tvComment.setVisibility(View.VISIBLE);
316 tvComment.requestFocus();
319 focused = tvAccount.requestFocus();
320 tvAccount.dismissDropDown();
322 Misc.showSoftKeyboard(
323 (NewTransactionActivity) tvAccount.getContext());
332 accountCountObserver = count -> {
333 final int adapterPosition = getAdapterPosition();
334 final int layoutPosition = getLayoutPosition();
335 Logger.debug("holder",
336 String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
337 adapterPosition, layoutPosition, item.getType()
339 .concat(item.getType() ==
340 ItemType.transactionRow
341 ? String.format(Locale.US,
347 ? String.format(Locale.US,
352 if (adapterPosition == count)
353 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
355 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
358 localeObserver = locale -> {
359 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
360 tvAmount.setKeyListener(DigitsKeyListener.getInstance(locale, true, true));
363 currencyObserver = currency -> {
364 setCurrency(currency);
365 adapter.checkTransactionSubmittable();
368 currencyGapObserver =
369 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
372 currencyPositionObserver =
373 position -> updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
375 showCurrencyObserver = showCurrency -> {
377 tvCurrency.setVisibility(View.VISIBLE);
380 tvCurrency.setVisibility(View.GONE);
381 item.setCurrency(null);
385 commentObserver = comment -> {
386 final View focusedView = tvComment.findFocus();
387 tvComment.setTypeface(null,
388 (focusedView == tvComment) ? Typeface.NORMAL : Typeface.ITALIC);
389 tvComment.setVisibility(
390 ((focusedView != tvComment) && Misc.isEmptyOrNull(comment)) ? View.INVISIBLE
394 showCommentsObserver = show -> {
395 final View amountLayout = itemView.findViewById(R.id.amount_layout);
396 ConstraintLayout.LayoutParams amountLayoutParams =
397 (ConstraintLayout.LayoutParams) amountLayout.getLayoutParams();
398 ConstraintLayout.LayoutParams accountParams =
399 (ConstraintLayout.LayoutParams) tvAccount.getLayoutParams();
401 commentLayout.setVisibility(View.VISIBLE);
403 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
404 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
406 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
407 amountLayoutParams.topToBottom = tvAccount.getId();
410 commentLayout.setVisibility(View.GONE);
412 accountParams.endToStart = amountLayout.getId();
413 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
415 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
416 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
420 tvAccount.setLayoutParams(accountParams);
421 amountLayout.setLayoutParams(amountLayoutParams);
423 transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
426 private void commentFocusChanged(View layout, TextView textView, boolean hasFocus) {
427 layout.setAlpha(hasFocus ? 1f : 0.5f);
428 textView.setTypeface(null, hasFocus ? Typeface.NORMAL : Typeface.ITALIC);
430 textView.setHint(R.string.transaction_account_comment_hint);
432 textView.setHint("");
434 if (!hasFocus && Misc.isEmptyOrNull(textView.getText()))
435 textView.setVisibility(View.INVISIBLE);
437 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
438 ConstraintLayout.LayoutParams amountLP =
439 (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
440 ConstraintLayout.LayoutParams currencyLP =
441 (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
443 if (position == Currency.Position.before) {
444 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
445 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
447 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
448 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
449 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
450 amountLP.startToEnd = tvCurrency.getId();
452 tvCurrency.setGravity(Gravity.END);
455 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
456 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
458 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
459 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
460 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
461 amountLP.endToStart = tvCurrency.getId();
463 tvCurrency.setGravity(Gravity.START);
466 amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
467 currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
469 tvAmount.setLayoutParams(amountLP);
470 tvCurrency.setLayoutParams(currencyLP);
472 // distance between the amount and the currency symbol
473 int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
475 if (position == Currency.Position.before) {
476 tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
479 tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
482 private void setCurrencyString(String currency) {
483 if ((currency == null) || currency.isEmpty()) {
484 tvCurrency.setText(R.string.currency_symbol);
485 tvCurrency.setTextColor(0x7f000000 + (0x00ffffff & Colors.defaultTextColor));
488 tvCurrency.setText(currency);
489 tvCurrency.setTextColor(Colors.defaultTextColor);
492 private void setCurrency(Currency currency) {
493 setCurrencyString((currency == null) ? null : currency.getName());
495 private void setEditable(Boolean editable) {
496 tvDate.setEnabled(editable);
497 tvDescription.setEnabled(editable);
498 tvAccount.setEnabled(editable);
499 tvAmount.setEnabled(editable);
501 private void beginUpdates() {
503 throw new RuntimeException("Already in update mode");
506 private void endUpdates() {
508 throw new RuntimeException("Not in update mode");
514 * Stores the data from the UI elements into the model item
515 * Returns true if there were changes made that suggest transaction has to be
516 * checked for being submittable
518 private boolean syncData() {
523 Logger.debug("new-trans", "skipping syncData() loop");
530 switch (item.getType()) {
532 item.setDate(String.valueOf(tvDate.getText()));
533 item.setDescription(String.valueOf(tvDescription.getText()));
536 final LedgerTransactionAccount account = item.getAccount();
537 account.setAccountName(String.valueOf(tvAccount.getText()));
539 item.setComment(String.valueOf(tvComment.getText()));
541 String amount = String.valueOf(tvAmount.getText());
542 amount = amount.trim();
544 if (amount.isEmpty()) {
545 account.resetAmount();
546 // account.setCurrency(null);
550 amount = amount.replace(decimalSeparator, decimalDot);
551 account.setAmount(Float.parseFloat(amount));
553 catch (NumberFormatException e) {
554 Logger.debug("new-trans", String.format(
555 "assuming amount is not set due to number format exception. " +
556 "input was '%s'", amount));
557 account.resetAmount();
559 final String curr = String.valueOf(tvCurrency.getText());
560 if (curr.equals(tvCurrency.getContext()
562 .getString(R.string.currency_symbol)) ||
564 account.setCurrency(null);
566 account.setCurrency(curr);
571 throw new RuntimeException("Should not happen");
580 private void pickTransactionDate() {
581 DatePickerFragment picker = new DatePickerFragment();
582 picker.setFutureDates(mProfile.getFutureDates());
583 picker.setOnDatePickedListener(this);
584 picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
590 * @param item updates the UI elements with the data from the model item
592 @SuppressLint("DefaultLocale")
593 public void setData(NewTransactionModel.Item item) {
596 if (this.item != null && !this.item.equals(item)) {
597 this.item.stopObservingDate(dateObserver);
598 this.item.stopObservingDescription(descriptionObserver);
599 this.item.stopObservingAmountHint(hintObserver);
600 this.item.stopObservingEditableFlag(editableObserver);
602 .stopObservingFocusedItem(focusedAccountObserver);
604 .stopObservingAccountCount(accountCountObserver);
605 Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
606 Data.currencyGap.removeObserver(currencyGapObserver);
607 Data.locale.removeObserver(localeObserver);
608 this.item.stopObservingCurrency(currencyObserver);
609 this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
610 this.item.stopObservingComment(commentObserver);
611 this.item.getModel().showComments.removeObserver(showCommentsObserver);
616 switch (item.getType()) {
618 tvDate.setText(item.getFormattedDate());
619 tvDescription.setText(item.getDescription());
620 lHead.setVisibility(View.VISIBLE);
621 lAccount.setVisibility(View.GONE);
622 lPadding.setVisibility(View.GONE);
626 LedgerTransactionAccount acc = item.getAccount();
627 tvAccount.setText(acc.getAccountName());
628 tvComment.setText(acc.getComment());
629 if (acc.isAmountSet()) {
630 tvAmount.setText(String.format("%1.2f", acc.getAmount()));
633 tvAmount.setText("");
634 // tvAmount.setHint(R.string.zero_amount);
636 tvAmount.setHint(item.getAmountHint());
637 setCurrencyString(acc.getCurrency());
638 lHead.setVisibility(View.GONE);
639 lAccount.setVisibility(View.VISIBLE);
640 lPadding.setVisibility(View.GONE);
644 lHead.setVisibility(View.GONE);
645 lAccount.setVisibility(View.GONE);
646 lPadding.setVisibility(View.VISIBLE);
650 if (this.item == null) { // was null or has changed
652 final NewTransactionActivity activity =
653 (NewTransactionActivity) tvDescription.getContext();
655 if (!item.isOfType(ItemType.bottomFiller)) {
656 item.observeEditableFlag(activity, editableObserver);
658 .observeFocusedItem(activity, focusedAccountObserver);
660 .observeShowComments(activity, showCommentsObserver);
662 switch (item.getType()) {
664 item.observeDate(activity, dateObserver);
665 item.observeDescription(activity, descriptionObserver);
668 item.observeAmountHint(activity, hintObserver);
669 Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
670 Data.currencyGap.observe(activity, currencyGapObserver);
671 Data.locale.observe(activity, localeObserver);
672 item.observeCurrency(activity, currencyObserver);
673 item.getModel().showCurrency.observe(activity, showCurrencyObserver);
674 item.observeComment(activity, commentObserver);
676 .observeAccountCount(activity, accountCountObserver);
686 public void onDatePicked(int year, int month, int day) {
687 final Calendar c = GregorianCalendar.getInstance();
688 c.set(year, month, day);
689 item.setDate(c.getTime());
690 boolean focused = tvDescription.requestFocus();
692 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
696 public void descriptionSelected(String description) {
697 tvAccount.setText(description);
698 tvAmount.requestFocus(View.FOCUS_FORWARD);