2 * Copyright © 2021 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.new_transaction;
20 import android.annotation.SuppressLint;
21 import android.graphics.Typeface;
22 import android.text.Editable;
23 import android.text.TextUtils;
24 import android.text.TextWatcher;
25 import android.view.Gravity;
26 import android.view.View;
27 import android.view.inputmethod.EditorInfo;
28 import android.widget.EditText;
29 import android.widget.TextView;
31 import androidx.annotation.ColorInt;
32 import androidx.annotation.NonNull;
33 import androidx.constraintlayout.widget.ConstraintLayout;
34 import androidx.recyclerview.widget.RecyclerView;
36 import net.ktnx.mobileledger.R;
37 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
38 import net.ktnx.mobileledger.databinding.NewTransactionRowBinding;
39 import net.ktnx.mobileledger.db.AccountAutocompleteAdapter;
40 import net.ktnx.mobileledger.model.Currency;
41 import net.ktnx.mobileledger.model.Data;
42 import net.ktnx.mobileledger.model.MobileLedgerProfile;
43 import net.ktnx.mobileledger.ui.CurrencySelectorFragment;
44 import net.ktnx.mobileledger.ui.DatePickerFragment;
45 import net.ktnx.mobileledger.ui.TextViewClearHelper;
46 import net.ktnx.mobileledger.utils.DimensionUtils;
47 import net.ktnx.mobileledger.utils.Logger;
48 import net.ktnx.mobileledger.utils.MLDB;
49 import net.ktnx.mobileledger.utils.Misc;
50 import net.ktnx.mobileledger.utils.SimpleDate;
52 import java.text.DecimalFormatSymbols;
53 import java.text.ParseException;
54 import java.util.Objects;
56 class NewTransactionItemHolder extends RecyclerView.ViewHolder
57 implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback {
58 private final String decimalDot;
59 private final MobileLedgerProfile mProfile;
60 private final NewTransactionRowBinding b;
61 private final NewTransactionItemsAdapter mAdapter;
62 private boolean ignoreFocusChanges = false;
63 private String decimalSeparator;
64 private boolean inUpdate = false;
65 private boolean syncingData = false;
66 //TODO multiple amounts with different currencies per posting?
67 NewTransactionItemHolder(@NonNull NewTransactionRowBinding b,
68 NewTransactionItemsAdapter adapter) {
71 this.mAdapter = adapter;
72 new TextViewClearHelper().attachToTextView(b.comment);
74 b.newTransactionDescription.setNextFocusForwardId(View.NO_ID);
75 b.accountRowAccName.setNextFocusForwardId(View.NO_ID);
76 b.accountRowAccAmounts.setNextFocusForwardId(View.NO_ID); // magic!
78 b.newTransactionDate.setOnClickListener(v -> pickTransactionDate());
80 b.accountCommentButton.setOnClickListener(v -> {
81 b.comment.setVisibility(View.VISIBLE);
82 b.comment.requestFocus();
85 b.transactionCommentButton.setOnClickListener(v -> {
86 b.transactionComment.setVisibility(View.VISIBLE);
87 b.transactionComment.requestFocus();
90 mProfile = Data.getProfile();
92 View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
93 final int id = v.getId();
95 boolean wasSyncing = syncingData;
98 final int pos = getAdapterPosition();
99 if (id == R.id.account_row_acc_name) {
100 adapter.noteFocusIsOnAccount(pos);
102 else if (id == R.id.account_row_acc_amounts) {
103 adapter.noteFocusIsOnAmount(pos);
105 else if (id == R.id.comment) {
106 adapter.noteFocusIsOnComment(pos);
108 else if (id == R.id.transaction_comment) {
109 adapter.noteFocusIsOnTransactionComment(pos);
111 else if (id == R.id.new_transaction_description) {
112 adapter.noteFocusIsOnDescription(pos);
115 throw new IllegalStateException("Where is the focus?");
118 syncingData = wasSyncing;
122 if (id == R.id.comment) {
123 commentFocusChanged(b.comment, hasFocus);
125 else if (id == R.id.transaction_comment) {
126 commentFocusChanged(b.transactionComment, hasFocus);
130 b.newTransactionDescription.setOnFocusChangeListener(focusMonitor);
131 b.accountRowAccName.setOnFocusChangeListener(focusMonitor);
132 b.accountRowAccAmounts.setOnFocusChangeListener(focusMonitor);
133 b.comment.setOnFocusChangeListener(focusMonitor);
134 b.transactionComment.setOnFocusChangeListener(focusMonitor);
136 NewTransactionActivity activity = (NewTransactionActivity) b.getRoot()
139 MLDB.hookAutocompletionAdapter(activity, b.newTransactionDescription,
140 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, activity, mProfile);
141 b.accountRowAccName.setAdapter(new AccountAutocompleteAdapter(b.getRoot()
142 .getContext(), mProfile));
144 decimalSeparator = "";
145 Data.locale.observe(activity, locale -> decimalSeparator = String.valueOf(
146 DecimalFormatSymbols.getInstance(locale)
147 .getMonetaryDecimalSeparator()));
151 final TextWatcher tw = new TextWatcher() {
153 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
157 public void onTextChanged(CharSequence s, int start, int before, int count) {
161 public void afterTextChanged(Editable s) {
162 // debug("input", "text changed");
166 Logger.debug("textWatcher", "calling syncData()");
168 Logger.debug("textWatcher",
169 "syncData() returned, checking if transaction is submittable");
170 adapter.model.checkTransactionSubmittable(null);
171 Logger.debug("textWatcher", "done");
174 final TextWatcher amountWatcher = new TextWatcher() {
176 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
178 public void onTextChanged(CharSequence s, int start, int before, int count) {}
180 public void afterTextChanged(Editable s) {
181 checkAmountValid(s.toString());
184 adapter.model.checkTransactionSubmittable(null);
187 b.newTransactionDescription.addTextChangedListener(tw);
188 monitorComment(b.transactionComment);
189 b.accountRowAccName.addTextChangedListener(tw);
190 monitorComment(b.comment);
191 b.accountRowAccAmounts.addTextChangedListener(amountWatcher);
193 b.currencyButton.setOnClickListener(v -> {
194 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
195 cpf.showPositionAndPadding();
196 cpf.setOnCurrencySelectedListener(
197 c -> adapter.setItemCurrency(getAdapterPosition(), c.getName()));
198 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
201 commentFocusChanged(b.transactionComment, false);
202 commentFocusChanged(b.comment, false);
204 adapter.model.getFocusInfo()
205 .observe(activity, focusInfo -> {
206 if (ignoreFocusChanges) {
207 Logger.debug("new-trans", "Ignoring focus change");
210 ignoreFocusChanges = true;
212 if (((focusInfo == null) ||
213 focusInfo.position != getAdapterPosition()) ||
217 NewTransactionModel.Item item = getItem();
218 if (item instanceof NewTransactionModel.TransactionHead) {
219 NewTransactionModel.TransactionHead head =
220 item.toTransactionHead();
221 // bad idea - double pop-up, and not really necessary.
222 // the user can tap the input to get the calendar
223 //if (!tvDate.hasFocus()) tvDate.requestFocus();
224 switch (focusInfo.element) {
225 case TransactionComment:
226 b.transactionComment.setVisibility(View.VISIBLE);
227 b.transactionComment.requestFocus();
231 b.newTransactionDescription.requestFocus();
232 // tvDescription.dismissDropDown();
234 Misc.showSoftKeyboard(
235 (NewTransactionActivity) b.getRoot()
240 else if (item instanceof NewTransactionModel.TransactionAccount) {
241 NewTransactionModel.TransactionAccount acc =
242 item.toTransactionAccount();
243 switch (focusInfo.element) {
245 b.accountRowAccAmounts.requestFocus();
248 b.comment.setVisibility(View.VISIBLE);
249 b.comment.requestFocus();
252 boolean focused = b.accountRowAccName.requestFocus();
253 // b.accountRowAccName.dismissDropDown();
255 Misc.showSoftKeyboard(
256 (NewTransactionActivity) b.getRoot()
263 ignoreFocusChanges = false;
266 adapter.model.getAccountCount()
267 .observe(activity, count -> {
268 final int adapterPosition = getAdapterPosition();
269 final int layoutPosition = getLayoutPosition();
271 if (adapterPosition == count)
272 b.accountRowAccAmounts.setImeOptions(EditorInfo.IME_ACTION_DONE);
274 b.accountRowAccAmounts.setImeOptions(EditorInfo.IME_ACTION_NEXT);
277 Data.currencyGap.observe(activity,
278 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
281 Data.currencySymbolPosition.observe(activity,
282 position -> updateCurrencyPositionAndPadding(position,
283 Data.currencyGap.getValue()));
285 adapter.model.getShowCurrency()
286 .observe(activity, showCurrency -> {
288 b.currency.setVisibility(View.VISIBLE);
289 b.currencyButton.setVisibility(View.VISIBLE);
290 b.currency.setText(mProfile.getDefaultCommodity());
293 b.currency.setVisibility(View.GONE);
294 b.currencyButton.setVisibility(View.GONE);
295 b.currency.setText(null);
299 adapter.model.getShowComments()
300 .observe(activity, show -> {
301 ConstraintLayout.LayoutParams amountLayoutParams =
302 (ConstraintLayout.LayoutParams) b.amountLayout.getLayoutParams();
303 ConstraintLayout.LayoutParams accountParams =
304 (ConstraintLayout.LayoutParams) b.accountRowAccName.getLayoutParams();
307 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
308 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
310 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
311 amountLayoutParams.topToBottom = b.accountRowAccName.getId();
313 b.commentLayout.setVisibility(View.VISIBLE);
316 accountParams.endToStart = b.amountLayout.getId();
317 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
319 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
320 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
322 b.commentLayout.setVisibility(View.GONE);
325 b.accountRowAccName.setLayoutParams(accountParams);
326 b.amountLayout.setLayoutParams(amountLayoutParams);
328 b.transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
331 public void checkAmountValid(String s) {
332 boolean valid = true;
334 if (s.length() > 0) {
335 float ignored = Float.parseFloat(s.replace(decimalSeparator, decimalDot));
338 catch (NumberFormatException ex) {
342 displayAmountValidity(valid);
344 private void displayAmountValidity(boolean valid) {
345 b.accountRowAccAmounts.setCompoundDrawablesRelativeWithIntrinsicBounds(
346 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
347 b.accountRowAccAmounts.setMinEms(valid ? 4 : 5);
349 private void monitorComment(EditText editText) {
350 editText.addTextChangedListener(new TextWatcher() {
352 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
355 public void onTextChanged(CharSequence s, int start, int before, int count) {
358 public void afterTextChanged(Editable s) {
359 // debug("input", "text changed");
363 Logger.debug("textWatcher", "calling syncData()");
365 Logger.debug("textWatcher",
366 "syncData() returned, checking if transaction is submittable");
367 styleComment(editText, s.toString());
368 Logger.debug("textWatcher", "done");
372 private void commentFocusChanged(TextView textView, boolean hasFocus) {
373 @ColorInt int textColor;
374 textColor = b.dummyText.getTextColors()
377 textView.setTypeface(null, Typeface.NORMAL);
378 textView.setHint(R.string.transaction_account_comment_hint);
381 int alpha = (textColor >> 24 & 0xff);
382 alpha = 3 * alpha / 4;
383 textColor = (alpha << 24) | (0x00ffffff & textColor);
384 textView.setTypeface(null, Typeface.ITALIC);
385 textView.setHint("");
386 if (TextUtils.isEmpty(textView.getText())) {
387 textView.setVisibility(View.INVISIBLE);
390 textView.setTextColor(textColor);
393 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
394 ConstraintLayout.LayoutParams amountLP =
395 (ConstraintLayout.LayoutParams) b.accountRowAccAmounts.getLayoutParams();
396 ConstraintLayout.LayoutParams currencyLP =
397 (ConstraintLayout.LayoutParams) b.currency.getLayoutParams();
399 if (position == Currency.Position.before) {
400 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
401 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
403 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
404 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
405 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
406 amountLP.startToEnd = b.currency.getId();
408 b.currency.setGravity(Gravity.END);
411 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
412 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
414 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
415 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
416 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
417 amountLP.endToStart = b.currency.getId();
419 b.currency.setGravity(Gravity.START);
422 amountLP.resolveLayoutDirection(b.accountRowAccAmounts.getLayoutDirection());
423 currencyLP.resolveLayoutDirection(b.currency.getLayoutDirection());
425 b.accountRowAccAmounts.setLayoutParams(amountLP);
426 b.currency.setLayoutParams(currencyLP);
428 // distance between the amount and the currency symbol
429 int gapSize = DimensionUtils.sp2px(b.currency.getContext(), 5);
431 if (position == Currency.Position.before) {
432 b.currency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
435 b.currency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
438 private void setCurrencyString(String currency) {
439 @ColorInt int textColor = b.dummyText.getTextColors()
441 if ((currency == null) || currency.isEmpty()) {
442 b.currency.setText(R.string.currency_symbol);
443 int alpha = (textColor >> 24) & 0xff;
444 alpha = alpha * 3 / 4;
445 b.currency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
448 b.currency.setText(currency);
449 b.currency.setTextColor(textColor);
452 private void setCurrency(Currency currency) {
453 setCurrencyString((currency == null) ? null : currency.getName());
455 private void setEditable(Boolean editable) {
456 b.newTransactionDate.setEnabled(editable);
457 b.newTransactionDescription.setEnabled(editable);
458 b.accountRowAccName.setEnabled(editable);
459 b.accountRowAccAmounts.setEnabled(editable);
461 private void beginUpdates() {
463 throw new RuntimeException("Already in update mode");
466 private void endUpdates() {
468 throw new RuntimeException("Not in update mode");
474 * Stores the data from the UI elements into the model item
475 * Returns true if there were changes made that suggest transaction has to be
476 * checked for being submittable
478 private boolean syncData() {
480 Logger.debug("new-trans", "skipping syncData() loop");
484 NewTransactionModel.Item item = getItem();
489 if (item instanceof NewTransactionModel.TransactionHead) {
490 NewTransactionModel.TransactionHead head = item.toTransactionHead();
492 head.setDate(String.valueOf(b.newTransactionDate.getText()));
493 head.setDescription(String.valueOf(b.newTransactionDescription.getText()));
494 head.setComment(String.valueOf(b.transactionComment.getText()));
496 else if (item instanceof NewTransactionModel.TransactionAccount) {
497 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
498 acc.setAccountName(String.valueOf(b.accountRowAccName.getText()));
500 acc.setComment(String.valueOf(b.comment.getText()));
502 String amount = String.valueOf(b.accountRowAccAmounts.getText());
503 amount = amount.trim();
505 if (amount.isEmpty()) {
507 acc.setAmountValid(true);
511 amount = amount.replace(decimalSeparator, decimalDot);
512 acc.setAmount(Float.parseFloat(amount));
513 acc.setAmountValid(true);
515 catch (NumberFormatException e) {
516 Logger.debug("new-trans", String.format(
517 "assuming amount is not set due to number format exception. " +
518 "input was '%s'", amount));
519 acc.setAmountValid(false);
521 final String curr = String.valueOf(b.currency.getText());
522 if (curr.equals(b.currency.getContext()
524 .getString(R.string.currency_symbol)) ||
526 acc.setCurrency(null);
528 acc.setCurrency(curr);
532 throw new RuntimeException("Should not happen");
537 catch (ParseException e) {
538 throw new RuntimeException("Should not happen", e);
544 private void pickTransactionDate() {
545 DatePickerFragment picker = new DatePickerFragment();
546 picker.setFutureDates(mProfile.getFutureDates());
547 picker.setOnDatePickedListener(this);
548 picker.setCurrentDateFromText(b.newTransactionDate.getText());
549 picker.show(((NewTransactionActivity) b.getRoot()
550 .getContext()).getSupportFragmentManager(), null);
555 * @param item updates the UI elements with the data from the model item
557 @SuppressLint("DefaultLocale")
558 public void bind(@NonNull NewTransactionModel.Item item) {
563 if (item instanceof NewTransactionModel.TransactionHead) {
564 NewTransactionModel.TransactionHead head = item.toTransactionHead();
565 b.newTransactionDate.setText(head.getFormattedDate());
566 b.newTransactionDescription.setText(head.getDescription());
568 b.transactionComment.setText(head.getComment());
569 //styleComment(b.transactionComment, head.getComment());
571 b.ntrData.setVisibility(View.VISIBLE);
572 b.ntrAccount.setVisibility(View.GONE);
573 b.ntrPadding.setVisibility(View.GONE);
576 else if (item instanceof NewTransactionModel.TransactionAccount) {
577 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
579 b.accountRowAccName.setText(acc.getAccountName());
581 final String amountHint = acc.getAmountHint();
582 if (amountHint == null) {
583 b.accountRowAccAmounts.setHint(R.string.zero_amount);
586 b.accountRowAccAmounts.setHint(amountHint);
589 setCurrencyString(acc.getCurrency());
590 b.accountRowAccAmounts.setText(
591 acc.isAmountSet() ? String.format("%4.2f", acc.getAmount()) : null);
592 displayAmountValidity(true);
594 b.comment.setText(acc.getComment());
596 b.ntrData.setVisibility(View.GONE);
597 b.ntrAccount.setVisibility(View.VISIBLE);
598 b.ntrPadding.setVisibility(View.GONE);
602 throw new RuntimeException("Don't know how to handle " + item);
613 private void styleComment(EditText editText, String comment) {
614 final View focusedView = editText.findFocus();
615 editText.setTypeface(null, (focusedView == editText) ? Typeface.NORMAL : Typeface.ITALIC);
616 editText.setVisibility(
617 ((focusedView != editText) && TextUtils.isEmpty(comment)) ? View.INVISIBLE
621 public void onDatePicked(int year, int month, int day) {
622 final NewTransactionModel.TransactionHead head = getItem().toTransactionHead();
623 head.setDate(new SimpleDate(year, month + 1, day));
624 b.newTransactionDate.setText(head.getFormattedDate());
626 boolean focused = b.newTransactionDescription.requestFocus();
628 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
632 private NewTransactionModel.Item getItem() {
633 return Objects.requireNonNull(mAdapter.model.getItems()
635 .get(getAdapterPosition());
638 public void descriptionSelected(String description) {
639 b.accountRowAccName.setText(description);
640 b.accountRowAccAmounts.requestFocus(View.FOCUS_FORWARD);