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.os.Build;
22 import android.text.Editable;
23 import android.text.TextWatcher;
24 import android.text.method.DigitsKeyListener;
25 import android.view.Gravity;
26 import android.view.View;
27 import android.view.ViewGroup;
28 import android.view.inputmethod.EditorInfo;
29 import android.widget.AutoCompleteTextView;
30 import android.widget.EditText;
31 import android.widget.FrameLayout;
32 import android.widget.LinearLayout;
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 org.jetbrains.annotations.NotNull;
58 import java.text.DecimalFormatSymbols;
59 import java.util.Calendar;
60 import java.util.Date;
61 import java.util.GregorianCalendar;
62 import java.util.Locale;
64 import static net.ktnx.mobileledger.ui.activity.NewTransactionModel.ItemType;
66 class NewTransactionItemHolder extends RecyclerView.ViewHolder
67 implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback {
68 private final String decimalSeparator;
69 private final String decimalDot;
70 private final TextView tvCurrency;
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 LinearLayout 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<Boolean> commentVisibleObserver;
89 private Observer<String> commentObserver;
90 private Observer<Currency.Position> currencyPositionObserver;
91 private Observer<Boolean> currencyGapObserver;
92 private Observer<Locale> localeObserver;
93 private Observer<Currency> currencyObserver;
94 private Observer<Boolean> showCurrencyObserver;
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);
113 tvDescription.setNextFocusForwardId(View.NO_ID);
114 tvAccount.setNextFocusForwardId(View.NO_ID);
115 tvAmount.setNextFocusForwardId(View.NO_ID); // magic!
117 tvDate.setOnClickListener(v -> pickTransactionDate());
119 mProfile = Data.profile.getValue();
120 if (mProfile == null)
121 throw new AssertionError();
123 View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
125 boolean wasSyncing = syncingData;
128 final int pos = getAdapterPosition();
129 adapter.updateFocusedItem(pos);
131 case R.id.account_row_acc_name:
132 adapter.noteFocusIsOnAccount(pos);
134 case R.id.account_row_acc_amounts:
135 adapter.noteFocusIsOnAmount(pos);
138 adapter.noteFocusIsOnComment(pos);
143 syncingData = wasSyncing;
148 tvDescription.setOnFocusChangeListener(focusMonitor);
149 tvAccount.setOnFocusChangeListener(focusMonitor);
150 tvAmount.setOnFocusChangeListener(focusMonitor);
152 itemView.findViewById(R.id.comment_button)
153 .setOnClickListener(v -> {
154 final int pos = getAdapterPosition();
155 adapter.toggleComment(pos);
157 MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
158 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
159 MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
160 "name", true, this, mProfile);
162 // FIXME: react on configuration (locale) changes
163 decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
164 .getMonetaryDecimalSeparator());
167 final TextWatcher tw = new TextWatcher() {
169 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
173 public void onTextChanged(CharSequence s, int start, int before, int count) {
177 public void afterTextChanged(Editable s) {
178 // debug("input", "text changed");
182 Logger.debug("textWatcher", "calling syncData()");
184 Logger.debug("textWatcher",
185 "syncData() returned, checking if transaction is submittable");
186 adapter.checkTransactionSubmittable();
187 Logger.debug("textWatcher", "done");
190 final TextWatcher amountWatcher = new TextWatcher() {
192 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
194 String.format(Locale.US, "beforeTextChanged: start=%d, count=%d, after=%d",
195 start, count, after));
198 public void onTextChanged(CharSequence s, int start, int before, int count) {}
200 public void afterTextChanged(Editable s) {
201 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
202 // only one decimal separator is allowed
203 // plus and minus are allowed only at the beginning
204 String allowed = "0123456789";
205 String val = s.toString();
206 Logger.debug("input", val);
207 if (val.isEmpty() || (tvAmount.getSelectionStart() == 0))
209 if (!val.contains(decimalSeparator) && !val.contains(decimalDot))
210 allowed += decimalSeparator + decimalDot;
212 tvAmount.setKeyListener(DigitsKeyListener.getInstance(allowed));
216 adapter.checkTransactionSubmittable();
219 tvDescription.addTextChangedListener(tw);
220 tvAccount.addTextChangedListener(tw);
221 tvComment.addTextChangedListener(tw);
222 tvAmount.addTextChangedListener(amountWatcher);
224 tvCurrency.setOnClickListener(v -> {
225 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
226 cpf.showPositionAndPadding();
227 cpf.setOnCurrencySelectedListener(c -> item.setCurrency(c));
228 final AppCompatActivity activity = (AppCompatActivity) v.getContext();
229 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
232 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
233 tvAmount.setKeyListener(
234 DigitsKeyListener.getInstance(Data.locale.getValue(), true, true));
236 tvAmount.setKeyListener(
237 DigitsKeyListener.getInstance("0123456789+-" + decimalSeparator + decimalDot));
239 dateObserver = date -> {
244 tvDate.setText(item.getFormattedDate());
250 descriptionObserver = description -> {
255 tvDescription.setText(description);
261 hintObserver = hint -> {
267 tvAmount.setHint(R.string.zero_amount);
269 tvAmount.setHint(hint);
275 editableObserver = this::setEditable;
276 commentVisibleObserver = this::setCommentVisible;
277 commentObserver = this::setComment;
278 focusedAccountObserver = index -> {
279 if ((index != null) && index.equals(getAdapterPosition())) {
280 switch (item.getType()) {
282 // bad idea - double pop-up, and not really necessary.
283 // the user can tap the input to get the calendar
284 //if (!tvDate.hasFocus()) tvDate.requestFocus();
285 boolean focused = tvDescription.requestFocus();
286 tvDescription.dismissDropDown();
288 Misc.showSoftKeyboard(
289 (NewTransactionActivity) tvDescription.getContext());
292 // do nothing if a row element already has the focus
293 if (!itemView.hasFocus()) {
294 switch (item.getFocusedElement()) {
296 tvAmount.requestFocus();
299 tvComment.requestFocus();
302 focused = tvAccount.requestFocus();
303 tvAccount.dismissDropDown();
305 Misc.showSoftKeyboard(
306 (NewTransactionActivity) tvAccount.getContext());
315 accountCountObserver = count -> {
316 final int adapterPosition = getAdapterPosition();
317 final int layoutPosition = getLayoutPosition();
318 Logger.debug("holder",
319 String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
320 adapterPosition, layoutPosition, item.getType()
322 .concat(item.getType() ==
323 ItemType.transactionRow
324 ? String.format(Locale.US,
330 ? String.format(Locale.US,
335 if (adapterPosition == count)
336 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
338 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
341 localeObserver = locale -> {
342 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
343 tvAmount.setKeyListener(DigitsKeyListener.getInstance(locale, true, true));
346 currencyObserver = currency -> {
347 setCurrency(currency);
348 adapter.checkTransactionSubmittable();
351 currencyGapObserver = hasGap -> {
352 updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(), hasGap);
355 currencyPositionObserver = position -> {
356 updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
359 showCurrencyObserver = showCurrency -> {
361 tvCurrency.setVisibility(View.VISIBLE);
364 tvCurrency.setVisibility(View.GONE);
365 item.setCurrency(null);
369 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
370 ConstraintLayout.LayoutParams amountLP =
371 (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
372 ConstraintLayout.LayoutParams currencyLP =
373 (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
375 if (position == Currency.Position.before) {
376 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
377 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
379 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
380 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
381 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
382 amountLP.startToEnd = tvCurrency.getId();
384 tvCurrency.setGravity(Gravity.END);
387 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
388 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
390 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
391 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
392 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
393 amountLP.endToStart = tvCurrency.getId();
395 tvCurrency.setGravity(Gravity.START);
398 amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
399 currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
401 tvAmount.setLayoutParams(amountLP);
402 tvCurrency.setLayoutParams(currencyLP);
404 // distance between the amount and the currency symbol
405 int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
407 if (position == Currency.Position.before) {
408 tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
411 tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
414 private void setCurrencyString(String currency) {
415 if ((currency == null) || currency.isEmpty()) {
416 tvCurrency.setText(R.string.currency_symbol);
417 tvCurrency.setTextColor(0x7f000000 + (0x00ffffff & Colors.defaultTextColor));
420 tvCurrency.setText(currency);
421 tvCurrency.setTextColor(Colors.defaultTextColor);
424 private void setCurrency(Currency currency) {
425 setCurrencyString((currency == null) ? null : currency.getName());
427 private void setEditable(Boolean editable) {
428 tvDate.setEnabled(editable);
429 tvDescription.setEnabled(editable);
430 tvAccount.setEnabled(editable);
431 tvAmount.setEnabled(editable);
433 private void setCommentVisible(@NotNull Boolean visible) {
435 // showing; show the comment view and align the comment button to it
436 tvComment.setVisibility(View.VISIBLE);
437 tvComment.requestFocus();
438 ConstraintLayout.LayoutParams lp =
439 (ConstraintLayout.LayoutParams) commentButton.getLayoutParams();
440 lp.bottomToBottom = R.id.comment;
442 commentButton.setLayoutParams(lp);
445 // hiding; hide the comment view and align the comment bottom to the amount
446 tvComment.setVisibility(View.GONE);
447 ConstraintLayout.LayoutParams lp =
448 (ConstraintLayout.LayoutParams) commentButton.getLayoutParams();
449 lp.bottomToBottom = R.id.amount_layout; // R.id.parent doesn't work here
451 commentButton.setLayoutParams(lp);
454 private void setComment(String comment) {
455 if ((comment != null) && !comment.isEmpty())
456 commentButton.setBackgroundResource(R.drawable.ic_comment_black_24dp);
458 commentButton.setBackgroundResource(R.drawable.ic_comment_gray_24dp);
460 private void beginUpdates() {
462 throw new RuntimeException("Already in update mode");
465 private void endUpdates() {
467 throw new RuntimeException("Not in update mode");
473 * Stores the data from the UI elements into the model item
474 * Returns true if there were changes made that suggest transaction has to be
475 * checked for being submittable
477 private boolean syncData() {
482 Logger.debug("new-trans", "skipping syncData() loop");
489 switch (item.getType()) {
491 item.setDate(String.valueOf(tvDate.getText()));
492 item.setDescription(String.valueOf(tvDescription.getText()));
495 final LedgerTransactionAccount account = item.getAccount();
496 account.setAccountName(String.valueOf(tvAccount.getText()));
498 item.setComment(String.valueOf(tvComment.getText()));
500 String amount = String.valueOf(tvAmount.getText());
501 amount = amount.trim();
503 if (amount.isEmpty()) {
504 account.resetAmount();
505 // account.setCurrency(null);
509 amount = amount.replace(decimalSeparator, decimalDot);
510 account.setAmount(Float.parseFloat(amount));
512 catch (NumberFormatException e) {
513 Logger.debug("new-trans", String.format(
514 "assuming amount is not set due to number format exception. " +
515 "input was '%s'", amount));
516 account.resetAmount();
518 final String curr = String.valueOf(tvCurrency.getText());
519 if (curr.equals(tvCurrency.getContext()
521 .getString(R.string.currency_symbol)) ||
523 account.setCurrency(null);
525 account.setCurrency(curr);
530 throw new RuntimeException("Should not happen");
539 private void pickTransactionDate() {
540 DatePickerFragment picker = new DatePickerFragment();
541 picker.setFutureDates(mProfile.getFutureDates());
542 picker.setOnDatePickedListener(this);
543 picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
549 * @param item updates the UI elements with the data from the model item
551 @SuppressLint("DefaultLocale")
552 public void setData(NewTransactionModel.Item item) {
555 if (this.item != null && !this.item.equals(item)) {
556 this.item.stopObservingDate(dateObserver);
557 this.item.stopObservingDescription(descriptionObserver);
558 this.item.stopObservingAmountHint(hintObserver);
559 this.item.stopObservingEditableFlag(editableObserver);
560 this.item.stopObservingCommentVisible(commentVisibleObserver);
561 this.item.stopObservingComment(commentObserver);
563 .stopObservingFocusedItem(focusedAccountObserver);
565 .stopObservingAccountCount(accountCountObserver);
566 Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
567 Data.currencyGap.removeObserver(currencyGapObserver);
568 Data.locale.removeObserver(localeObserver);
569 this.item.stopObservingCurrency(currencyObserver);
570 this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
575 switch (item.getType()) {
577 tvDate.setText(item.getFormattedDate());
578 tvDescription.setText(item.getDescription());
579 lHead.setVisibility(View.VISIBLE);
580 lAccount.setVisibility(View.GONE);
581 lPadding.setVisibility(View.GONE);
585 LedgerTransactionAccount acc = item.getAccount();
586 tvAccount.setText(acc.getAccountName());
587 tvComment.setText(acc.getComment());
588 if (acc.isAmountSet()) {
589 tvAmount.setText(String.format("%1.2f", acc.getAmount()));
592 tvAmount.setText("");
593 // tvAmount.setHint(R.string.zero_amount);
595 tvAmount.setHint(item.getAmountHint());
596 setCurrencyString(acc.getCurrency());
597 lHead.setVisibility(View.GONE);
598 lAccount.setVisibility(View.VISIBLE);
599 lPadding.setVisibility(View.GONE);
603 lHead.setVisibility(View.GONE);
604 lAccount.setVisibility(View.GONE);
605 lPadding.setVisibility(View.VISIBLE);
609 if (this.item == null) { // was null or has changed
611 final NewTransactionActivity activity =
612 (NewTransactionActivity) tvDescription.getContext();
614 if (!item.isOfType(ItemType.bottomFiller)) {
615 item.observeEditableFlag(activity, editableObserver);
617 .observeFocusedItem(activity, focusedAccountObserver);
619 switch (item.getType()) {
621 item.observeDate(activity, dateObserver);
622 item.observeDescription(activity, descriptionObserver);
625 item.observeAmountHint(activity, hintObserver);
626 item.observeCommentVisible(activity, commentVisibleObserver);
627 item.observeComment(activity, commentObserver);
628 Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
629 Data.currencyGap.observe(activity, currencyGapObserver);
630 Data.locale.observe(activity, localeObserver);
631 item.observeCurrency(activity, currencyObserver);
632 item.getModel().showCurrency.observe(activity, showCurrencyObserver);
634 .observeAccountCount(activity, accountCountObserver);
644 public void onDatePicked(int year, int month, int day) {
645 final Calendar c = GregorianCalendar.getInstance();
646 c.set(year, month, day);
647 item.setDate(c.getTime());
648 boolean focused = tvDescription.requestFocus();
650 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
654 public void descriptionSelected(String description) {
655 tvAccount.setText(description);
656 tvAmount.requestFocus(View.FOCUS_FORWARD);