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.LinearLayout;
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 LinearLayout 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 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 tvAccount = itemView.findViewById(R.id.account_row_acc_name);
102 tvComment = itemView.findViewById(R.id.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 View commentLayout = itemView.findViewById(R.id.comment_layout);
114 tvDescription.setNextFocusForwardId(View.NO_ID);
115 tvAccount.setNextFocusForwardId(View.NO_ID);
116 tvAmount.setNextFocusForwardId(View.NO_ID); // magic!
118 tvDate.setOnClickListener(v -> pickTransactionDate());
120 itemView.findViewById(R.id.comment_button)
121 .setOnClickListener(v -> {
122 tvComment.setVisibility(View.VISIBLE);
123 tvComment.requestFocus();
126 mProfile = Data.profile.getValue();
127 if (mProfile == null)
128 throw new AssertionError();
130 View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
131 final int id = v.getId();
133 boolean wasSyncing = syncingData;
136 final int pos = getAdapterPosition();
137 adapter.updateFocusedItem(pos);
139 case R.id.account_row_acc_name:
140 adapter.noteFocusIsOnAccount(pos);
142 case R.id.account_row_acc_amounts:
143 adapter.noteFocusIsOnAmount(pos);
146 adapter.noteFocusIsOnComment(pos);
151 syncingData = wasSyncing;
155 if (id == R.id.comment) {
156 commentLayout.setAlpha(hasFocus ? 1f : 0.5f);
157 tvComment.setTypeface(null, hasFocus ? Typeface.NORMAL : Typeface.ITALIC);
159 tvComment.setHint(R.string.transaction_account_comment_hint);
161 tvComment.setHint("");
163 if (!hasFocus && Misc.isEmptyOrNull(tvComment.getText()))
164 tvComment.setVisibility(View.INVISIBLE);
168 tvDescription.setOnFocusChangeListener(focusMonitor);
169 tvAccount.setOnFocusChangeListener(focusMonitor);
170 tvAmount.setOnFocusChangeListener(focusMonitor);
171 tvComment.setOnFocusChangeListener(focusMonitor);
173 MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
174 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
175 MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
176 "name", true, this, mProfile);
178 // FIXME: react on configuration (locale) changes
179 decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
180 .getMonetaryDecimalSeparator());
183 final TextWatcher tw = new TextWatcher() {
185 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
189 public void onTextChanged(CharSequence s, int start, int before, int count) {
193 public void afterTextChanged(Editable s) {
194 // debug("input", "text changed");
198 Logger.debug("textWatcher", "calling syncData()");
200 Logger.debug("textWatcher",
201 "syncData() returned, checking if transaction is submittable");
202 adapter.checkTransactionSubmittable();
203 Logger.debug("textWatcher", "done");
206 final TextWatcher amountWatcher = new TextWatcher() {
208 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
210 String.format(Locale.US, "beforeTextChanged: start=%d, count=%d, after=%d",
211 start, count, after));
214 public void onTextChanged(CharSequence s, int start, int before, int count) {}
216 public void afterTextChanged(Editable s) {
217 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
218 // only one decimal separator is allowed
219 // plus and minus are allowed only at the beginning
220 String allowed = "0123456789";
221 String val = s.toString();
222 Logger.debug("input", val);
223 if (val.isEmpty() || (tvAmount.getSelectionStart() == 0))
225 if (!val.contains(decimalSeparator) && !val.contains(decimalDot))
226 allowed += decimalSeparator + decimalDot;
228 tvAmount.setKeyListener(DigitsKeyListener.getInstance(allowed));
232 adapter.checkTransactionSubmittable();
235 tvDescription.addTextChangedListener(tw);
236 tvAccount.addTextChangedListener(tw);
237 tvComment.addTextChangedListener(tw);
238 tvAmount.addTextChangedListener(amountWatcher);
240 tvCurrency.setOnClickListener(v -> {
241 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
242 cpf.showPositionAndPadding();
243 cpf.setOnCurrencySelectedListener(c -> item.setCurrency(c));
244 final AppCompatActivity activity = (AppCompatActivity) v.getContext();
245 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
248 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
249 tvAmount.setKeyListener(
250 DigitsKeyListener.getInstance(Data.locale.getValue(), true, true));
252 tvAmount.setKeyListener(
253 DigitsKeyListener.getInstance("0123456789+-" + decimalSeparator + decimalDot));
255 dateObserver = date -> {
260 tvDate.setText(item.getFormattedDate());
266 descriptionObserver = description -> {
271 tvDescription.setText(description);
277 hintObserver = hint -> {
283 tvAmount.setHint(R.string.zero_amount);
285 tvAmount.setHint(hint);
291 editableObserver = this::setEditable;
292 focusedAccountObserver = index -> {
293 if ((index != null) && index.equals(getAdapterPosition())) {
294 switch (item.getType()) {
296 // bad idea - double pop-up, and not really necessary.
297 // the user can tap the input to get the calendar
298 //if (!tvDate.hasFocus()) tvDate.requestFocus();
299 boolean focused = tvDescription.requestFocus();
300 tvDescription.dismissDropDown();
302 Misc.showSoftKeyboard(
303 (NewTransactionActivity) tvDescription.getContext());
306 // do nothing if a row element already has the focus
307 if (!itemView.hasFocus()) {
308 switch (item.getFocusedElement()) {
310 tvAmount.requestFocus();
313 tvComment.requestFocus();
316 focused = tvAccount.requestFocus();
317 tvAccount.dismissDropDown();
319 Misc.showSoftKeyboard(
320 (NewTransactionActivity) tvAccount.getContext());
329 accountCountObserver = count -> {
330 final int adapterPosition = getAdapterPosition();
331 final int layoutPosition = getLayoutPosition();
332 Logger.debug("holder",
333 String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
334 adapterPosition, layoutPosition, item.getType()
336 .concat(item.getType() ==
337 ItemType.transactionRow
338 ? String.format(Locale.US,
344 ? String.format(Locale.US,
349 if (adapterPosition == count)
350 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
352 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
355 localeObserver = locale -> {
356 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
357 tvAmount.setKeyListener(DigitsKeyListener.getInstance(locale, true, true));
360 currencyObserver = currency -> {
361 setCurrency(currency);
362 adapter.checkTransactionSubmittable();
365 currencyGapObserver =
366 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
369 currencyPositionObserver =
370 position -> updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
372 showCurrencyObserver = showCurrency -> {
374 tvCurrency.setVisibility(View.VISIBLE);
377 tvCurrency.setVisibility(View.GONE);
378 item.setCurrency(null);
382 commentObserver = comment -> {
383 final View focusedView = tvComment.findFocus();
384 tvComment.setTypeface(null,
385 (focusedView == tvComment) ? Typeface.NORMAL : Typeface.ITALIC);
386 tvComment.setVisibility(
387 ((focusedView != tvComment) && Misc.isEmptyOrNull(comment)) ? View.INVISIBLE
391 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
392 ConstraintLayout.LayoutParams amountLP =
393 (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
394 ConstraintLayout.LayoutParams currencyLP =
395 (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
397 if (position == Currency.Position.before) {
398 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
399 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
401 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
402 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
403 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
404 amountLP.startToEnd = tvCurrency.getId();
406 tvCurrency.setGravity(Gravity.END);
409 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
410 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
412 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
413 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
414 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
415 amountLP.endToStart = tvCurrency.getId();
417 tvCurrency.setGravity(Gravity.START);
420 amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
421 currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
423 tvAmount.setLayoutParams(amountLP);
424 tvCurrency.setLayoutParams(currencyLP);
426 // distance between the amount and the currency symbol
427 int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
429 if (position == Currency.Position.before) {
430 tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
433 tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
436 private void setCurrencyString(String currency) {
437 if ((currency == null) || currency.isEmpty()) {
438 tvCurrency.setText(R.string.currency_symbol);
439 tvCurrency.setTextColor(0x7f000000 + (0x00ffffff & Colors.defaultTextColor));
442 tvCurrency.setText(currency);
443 tvCurrency.setTextColor(Colors.defaultTextColor);
446 private void setCurrency(Currency currency) {
447 setCurrencyString((currency == null) ? null : currency.getName());
449 private void setEditable(Boolean editable) {
450 tvDate.setEnabled(editable);
451 tvDescription.setEnabled(editable);
452 tvAccount.setEnabled(editable);
453 tvAmount.setEnabled(editable);
455 private void setCommentVisible(@NotNull Boolean visible) {
457 // showing; show the comment view and align the comment button to it
458 tvComment.setVisibility(View.VISIBLE);
459 tvComment.requestFocus();
460 ConstraintLayout.LayoutParams lp =
461 (ConstraintLayout.LayoutParams) commentButton.getLayoutParams();
462 lp.bottomToBottom = R.id.comment;
464 commentButton.setLayoutParams(lp);
467 // hiding; hide the comment view and align the comment bottom to the amount
468 tvComment.setVisibility(View.GONE);
469 ConstraintLayout.LayoutParams lp =
470 (ConstraintLayout.LayoutParams) commentButton.getLayoutParams();
471 lp.bottomToBottom = R.id.amount_layout; // R.id.parent doesn't work here
473 commentButton.setLayoutParams(lp);
476 private void beginUpdates() {
478 throw new RuntimeException("Already in update mode");
481 private void endUpdates() {
483 throw new RuntimeException("Not in update mode");
489 * Stores the data from the UI elements into the model item
490 * Returns true if there were changes made that suggest transaction has to be
491 * checked for being submittable
493 private boolean syncData() {
498 Logger.debug("new-trans", "skipping syncData() loop");
505 switch (item.getType()) {
507 item.setDate(String.valueOf(tvDate.getText()));
508 item.setDescription(String.valueOf(tvDescription.getText()));
511 final LedgerTransactionAccount account = item.getAccount();
512 account.setAccountName(String.valueOf(tvAccount.getText()));
514 item.setComment(String.valueOf(tvComment.getText()));
516 String amount = String.valueOf(tvAmount.getText());
517 amount = amount.trim();
519 if (amount.isEmpty()) {
520 account.resetAmount();
521 // account.setCurrency(null);
525 amount = amount.replace(decimalSeparator, decimalDot);
526 account.setAmount(Float.parseFloat(amount));
528 catch (NumberFormatException e) {
529 Logger.debug("new-trans", String.format(
530 "assuming amount is not set due to number format exception. " +
531 "input was '%s'", amount));
532 account.resetAmount();
534 final String curr = String.valueOf(tvCurrency.getText());
535 if (curr.equals(tvCurrency.getContext()
537 .getString(R.string.currency_symbol)) ||
539 account.setCurrency(null);
541 account.setCurrency(curr);
546 throw new RuntimeException("Should not happen");
555 private void pickTransactionDate() {
556 DatePickerFragment picker = new DatePickerFragment();
557 picker.setFutureDates(mProfile.getFutureDates());
558 picker.setOnDatePickedListener(this);
559 picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
565 * @param item updates the UI elements with the data from the model item
567 @SuppressLint("DefaultLocale")
568 public void setData(NewTransactionModel.Item item) {
571 if (this.item != null && !this.item.equals(item)) {
572 this.item.stopObservingDate(dateObserver);
573 this.item.stopObservingDescription(descriptionObserver);
574 this.item.stopObservingAmountHint(hintObserver);
575 this.item.stopObservingEditableFlag(editableObserver);
577 .stopObservingFocusedItem(focusedAccountObserver);
579 .stopObservingAccountCount(accountCountObserver);
580 Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
581 Data.currencyGap.removeObserver(currencyGapObserver);
582 Data.locale.removeObserver(localeObserver);
583 this.item.stopObservingCurrency(currencyObserver);
584 this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
585 this.item.stopObservingComment(commentObserver);
590 switch (item.getType()) {
592 tvDate.setText(item.getFormattedDate());
593 tvDescription.setText(item.getDescription());
594 lHead.setVisibility(View.VISIBLE);
595 lAccount.setVisibility(View.GONE);
596 lPadding.setVisibility(View.GONE);
600 LedgerTransactionAccount acc = item.getAccount();
601 tvAccount.setText(acc.getAccountName());
602 tvComment.setText(acc.getComment());
603 if (acc.isAmountSet()) {
604 tvAmount.setText(String.format("%1.2f", acc.getAmount()));
607 tvAmount.setText("");
608 // tvAmount.setHint(R.string.zero_amount);
610 tvAmount.setHint(item.getAmountHint());
611 setCurrencyString(acc.getCurrency());
612 lHead.setVisibility(View.GONE);
613 lAccount.setVisibility(View.VISIBLE);
614 lPadding.setVisibility(View.GONE);
618 lHead.setVisibility(View.GONE);
619 lAccount.setVisibility(View.GONE);
620 lPadding.setVisibility(View.VISIBLE);
624 if (this.item == null) { // was null or has changed
626 final NewTransactionActivity activity =
627 (NewTransactionActivity) tvDescription.getContext();
629 if (!item.isOfType(ItemType.bottomFiller)) {
630 item.observeEditableFlag(activity, editableObserver);
632 .observeFocusedItem(activity, focusedAccountObserver);
634 switch (item.getType()) {
636 item.observeDate(activity, dateObserver);
637 item.observeDescription(activity, descriptionObserver);
640 item.observeAmountHint(activity, hintObserver);
641 Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
642 Data.currencyGap.observe(activity, currencyGapObserver);
643 Data.locale.observe(activity, localeObserver);
644 item.observeCurrency(activity, currencyObserver);
645 item.getModel().showCurrency.observe(activity, showCurrencyObserver);
646 item.observeComment(activity, commentObserver);
648 .observeAccountCount(activity, accountCountObserver);
658 public void onDatePicked(int year, int month, int day) {
659 final Calendar c = GregorianCalendar.getInstance();
660 c.set(year, month, day);
661 item.setDate(c.getTime());
662 boolean focused = tvDescription.requestFocus();
664 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
668 public void descriptionSelected(String description) {
669 tvAccount.setText(description);
670 tvAmount.requestFocus(View.FOCUS_FORWARD);