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.ProgressBar;
34 import android.widget.TextView;
36 import androidx.annotation.NonNull;
37 import androidx.appcompat.app.AppCompatActivity;
38 import androidx.constraintlayout.widget.ConstraintLayout;
39 import androidx.lifecycle.Observer;
40 import androidx.recyclerview.widget.RecyclerView;
42 import net.ktnx.mobileledger.R;
43 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
44 import net.ktnx.mobileledger.model.Currency;
45 import net.ktnx.mobileledger.model.Data;
46 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
47 import net.ktnx.mobileledger.model.MobileLedgerProfile;
48 import net.ktnx.mobileledger.ui.CurrencySelectorFragment;
49 import net.ktnx.mobileledger.ui.DatePickerFragment;
50 import net.ktnx.mobileledger.ui.TextViewClearHelper;
51 import net.ktnx.mobileledger.utils.Colors;
52 import net.ktnx.mobileledger.utils.DimensionUtils;
53 import net.ktnx.mobileledger.utils.Logger;
54 import net.ktnx.mobileledger.utils.MLDB;
55 import net.ktnx.mobileledger.utils.Misc;
57 import org.jetbrains.annotations.NotNull;
59 import java.text.DecimalFormatSymbols;
60 import java.util.Calendar;
61 import java.util.Date;
62 import java.util.GregorianCalendar;
63 import java.util.Locale;
65 import static net.ktnx.mobileledger.ui.activity.NewTransactionModel.ItemType;
67 class NewTransactionItemHolder extends RecyclerView.ViewHolder
68 implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback {
69 private final String decimalSeparator;
70 private final String decimalDot;
71 private final TextView tvCurrency;
72 private NewTransactionModel.Item item;
73 private TextView tvDate;
74 private AutoCompleteTextView tvDescription;
75 private AutoCompleteTextView tvAccount;
76 private TextView tvComment;
77 private EditText tvAmount;
78 private ViewGroup lHead;
79 private ViewGroup lAccount;
80 private FrameLayout lPadding;
81 private MobileLedgerProfile mProfile;
83 private Observer<Date> dateObserver;
84 private Observer<String> descriptionObserver;
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> busyFlagObserver;
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 tvAccount = itemView.findViewById(R.id.account_row_acc_name);
103 tvComment = itemView.findViewById(R.id.comment);
104 new TextViewClearHelper().attachToTextView((EditText) tvComment);
105 commentButton = itemView.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 lAccount = itemView.findViewById(R.id.ntr_account);
112 lPadding = itemView.findViewById(R.id.ntr_padding);
113 View commentLayout = itemView.findViewById(R.id.comment_layout);
114 ProgressBar p = itemView.findViewById(R.id.progressBar);
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 itemView.findViewById(R.id.comment_button)
123 .setOnClickListener(v -> {
124 tvComment.setVisibility(View.VISIBLE);
125 tvComment.requestFocus();
128 mProfile = Data.profile.getValue();
129 if (mProfile == null)
130 throw new AssertionError();
132 View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
133 final int id = v.getId();
135 boolean wasSyncing = syncingData;
138 final int pos = getAdapterPosition();
139 adapter.updateFocusedItem(pos);
141 case R.id.account_row_acc_name:
142 adapter.noteFocusIsOnAccount(pos);
144 case R.id.account_row_acc_amounts:
145 adapter.noteFocusIsOnAmount(pos);
148 adapter.noteFocusIsOnComment(pos);
153 syncingData = wasSyncing;
157 if (id == R.id.comment) {
158 commentLayout.setAlpha(hasFocus ? 1f : 0.5f);
159 tvComment.setTypeface(null, hasFocus ? Typeface.NORMAL : Typeface.ITALIC);
161 tvComment.setHint(R.string.transaction_account_comment_hint);
163 tvComment.setHint("");
165 if (!hasFocus && Misc.isEmptyOrNull(tvComment.getText()))
166 tvComment.setVisibility(View.INVISIBLE);
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.requestFocus();
318 focused = tvAccount.requestFocus();
319 tvAccount.dismissDropDown();
321 Misc.showSoftKeyboard(
322 (NewTransactionActivity) tvAccount.getContext());
331 accountCountObserver = count -> {
332 final int adapterPosition = getAdapterPosition();
333 final int layoutPosition = getLayoutPosition();
334 Logger.debug("holder",
335 String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
336 adapterPosition, layoutPosition, item.getType()
338 .concat(item.getType() ==
339 ItemType.transactionRow
340 ? String.format(Locale.US,
346 ? String.format(Locale.US,
351 if (adapterPosition == count)
352 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
354 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
357 localeObserver = locale -> {
358 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
359 tvAmount.setKeyListener(DigitsKeyListener.getInstance(locale, true, true));
362 currencyObserver = currency -> {
363 setCurrency(currency);
364 adapter.checkTransactionSubmittable();
367 currencyGapObserver =
368 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
371 currencyPositionObserver =
372 position -> updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
374 showCurrencyObserver = showCurrency -> {
376 tvCurrency.setVisibility(View.VISIBLE);
379 tvCurrency.setVisibility(View.GONE);
380 item.setCurrency(null);
384 commentObserver = comment -> {
385 final View focusedView = tvComment.findFocus();
386 tvComment.setTypeface(null,
387 (focusedView == tvComment) ? Typeface.NORMAL : Typeface.ITALIC);
388 tvComment.setVisibility(
389 ((focusedView != tvComment) && Misc.isEmptyOrNull(comment)) ? View.INVISIBLE
393 busyFlagObserver = isBusy -> {p.setVisibility(isBusy ? View.VISIBLE : View.INVISIBLE);};
395 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
396 ConstraintLayout.LayoutParams amountLP =
397 (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
398 ConstraintLayout.LayoutParams currencyLP =
399 (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
401 if (position == Currency.Position.before) {
402 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
403 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
405 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
406 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
407 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
408 amountLP.startToEnd = tvCurrency.getId();
410 tvCurrency.setGravity(Gravity.END);
413 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
414 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
416 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
417 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
418 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
419 amountLP.endToStart = tvCurrency.getId();
421 tvCurrency.setGravity(Gravity.START);
424 amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
425 currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
427 tvAmount.setLayoutParams(amountLP);
428 tvCurrency.setLayoutParams(currencyLP);
430 // distance between the amount and the currency symbol
431 int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
433 if (position == Currency.Position.before) {
434 tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
437 tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
440 private void setCurrencyString(String currency) {
441 if ((currency == null) || currency.isEmpty()) {
442 tvCurrency.setText(R.string.currency_symbol);
443 tvCurrency.setTextColor(0x7f000000 + (0x00ffffff & Colors.defaultTextColor));
446 tvCurrency.setText(currency);
447 tvCurrency.setTextColor(Colors.defaultTextColor);
450 private void setCurrency(Currency currency) {
451 setCurrencyString((currency == null) ? null : currency.getName());
453 private void setEditable(Boolean editable) {
454 tvDate.setEnabled(editable);
455 tvDescription.setEnabled(editable);
456 tvAccount.setEnabled(editable);
457 tvAmount.setEnabled(editable);
459 private void setCommentVisible(@NotNull Boolean visible) {
461 // showing; show the comment view and align the comment button to it
462 tvComment.setVisibility(View.VISIBLE);
463 tvComment.requestFocus();
464 ConstraintLayout.LayoutParams lp =
465 (ConstraintLayout.LayoutParams) commentButton.getLayoutParams();
466 lp.bottomToBottom = R.id.comment;
468 commentButton.setLayoutParams(lp);
471 // hiding; hide the comment view and align the comment bottom to the amount
472 tvComment.setVisibility(View.GONE);
473 ConstraintLayout.LayoutParams lp =
474 (ConstraintLayout.LayoutParams) commentButton.getLayoutParams();
475 lp.bottomToBottom = R.id.amount_layout; // R.id.parent doesn't work here
477 commentButton.setLayoutParams(lp);
480 private void beginUpdates() {
482 throw new RuntimeException("Already in update mode");
485 private void endUpdates() {
487 throw new RuntimeException("Not in update mode");
493 * Stores the data from the UI elements into the model item
494 * Returns true if there were changes made that suggest transaction has to be
495 * checked for being submittable
497 private boolean syncData() {
502 Logger.debug("new-trans", "skipping syncData() loop");
509 switch (item.getType()) {
511 item.setDate(String.valueOf(tvDate.getText()));
512 item.setDescription(String.valueOf(tvDescription.getText()));
515 final LedgerTransactionAccount account = item.getAccount();
516 account.setAccountName(String.valueOf(tvAccount.getText()));
518 item.setComment(String.valueOf(tvComment.getText()));
520 String amount = String.valueOf(tvAmount.getText());
521 amount = amount.trim();
523 if (amount.isEmpty()) {
524 account.resetAmount();
525 // account.setCurrency(null);
529 amount = amount.replace(decimalSeparator, decimalDot);
530 account.setAmount(Float.parseFloat(amount));
532 catch (NumberFormatException e) {
533 Logger.debug("new-trans", String.format(
534 "assuming amount is not set due to number format exception. " +
535 "input was '%s'", amount));
536 account.resetAmount();
538 final String curr = String.valueOf(tvCurrency.getText());
539 if (curr.equals(tvCurrency.getContext()
541 .getString(R.string.currency_symbol)) ||
543 account.setCurrency(null);
545 account.setCurrency(curr);
550 throw new RuntimeException("Should not happen");
559 private void pickTransactionDate() {
560 DatePickerFragment picker = new DatePickerFragment();
561 picker.setFutureDates(mProfile.getFutureDates());
562 picker.setOnDatePickedListener(this);
563 picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
569 * @param item updates the UI elements with the data from the model item
571 @SuppressLint("DefaultLocale")
572 public void setData(NewTransactionModel.Item item) {
575 if (this.item != null && !this.item.equals(item)) {
576 this.item.stopObservingDate(dateObserver);
577 this.item.stopObservingDescription(descriptionObserver);
578 this.item.stopObservingAmountHint(hintObserver);
579 this.item.stopObservingEditableFlag(editableObserver);
581 .stopObservingFocusedItem(focusedAccountObserver);
583 .stopObservingAccountCount(accountCountObserver);
584 Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
585 Data.currencyGap.removeObserver(currencyGapObserver);
586 Data.locale.removeObserver(localeObserver);
587 this.item.stopObservingCurrency(currencyObserver);
588 this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
589 this.item.stopObservingComment(commentObserver);
590 this.item.getModel().stopObservingBusyFlag(busyFlagObserver);
595 switch (item.getType()) {
597 tvDate.setText(item.getFormattedDate());
598 tvDescription.setText(item.getDescription());
599 lHead.setVisibility(View.VISIBLE);
600 lAccount.setVisibility(View.GONE);
601 lPadding.setVisibility(View.GONE);
605 LedgerTransactionAccount acc = item.getAccount();
606 tvAccount.setText(acc.getAccountName());
607 tvComment.setText(acc.getComment());
608 if (acc.isAmountSet()) {
609 tvAmount.setText(String.format("%1.2f", acc.getAmount()));
612 tvAmount.setText("");
613 // tvAmount.setHint(R.string.zero_amount);
615 tvAmount.setHint(item.getAmountHint());
616 setCurrencyString(acc.getCurrency());
617 lHead.setVisibility(View.GONE);
618 lAccount.setVisibility(View.VISIBLE);
619 lPadding.setVisibility(View.GONE);
623 lHead.setVisibility(View.GONE);
624 lAccount.setVisibility(View.GONE);
625 lPadding.setVisibility(View.VISIBLE);
629 if (this.item == null) { // was null or has changed
631 final NewTransactionActivity activity =
632 (NewTransactionActivity) tvDescription.getContext();
634 if (!item.isOfType(ItemType.bottomFiller)) {
635 item.observeEditableFlag(activity, editableObserver);
637 .observeFocusedItem(activity, focusedAccountObserver);
639 switch (item.getType()) {
641 item.observeDate(activity, dateObserver);
642 item.observeDescription(activity, descriptionObserver);
643 item.getModel().observeBusyFlag(activity, busyFlagObserver);
646 item.observeAmountHint(activity, hintObserver);
647 Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
648 Data.currencyGap.observe(activity, currencyGapObserver);
649 Data.locale.observe(activity, localeObserver);
650 item.observeCurrency(activity, currencyObserver);
651 item.getModel().showCurrency.observe(activity, showCurrencyObserver);
652 item.observeComment(activity, commentObserver);
654 .observeAccountCount(activity, accountCountObserver);
664 public void onDatePicked(int year, int month, int day) {
665 final Calendar c = GregorianCalendar.getInstance();
666 c.set(year, month, day);
667 item.setDate(c.getTime());
668 boolean focused = tvDescription.requestFocus();
670 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
674 public void descriptionSelected(String description) {
675 tvAccount.setText(description);
676 tvAmount.requestFocus(View.FOCUS_FORWARD);