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 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 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 new TextViewClearHelper().attachToTextView((EditText) tvComment);
103 commentButton = itemView.findViewById(R.id.comment_button);
104 tvAmount = itemView.findViewById(R.id.account_row_acc_amounts);
105 tvCurrency = itemView.findViewById(R.id.currency);
106 tvDate = itemView.findViewById(R.id.new_transaction_date);
107 tvDescription = itemView.findViewById(R.id.new_transaction_description);
108 lHead = itemView.findViewById(R.id.ntr_data);
109 lAccount = itemView.findViewById(R.id.ntr_account);
110 lPadding = itemView.findViewById(R.id.ntr_padding);
111 View commentLayout = itemView.findViewById(R.id.comment_layout);
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 itemView.findViewById(R.id.comment_button)
120 .setOnClickListener(v -> {
121 tvComment.setVisibility(View.VISIBLE);
122 tvComment.requestFocus();
125 mProfile = Data.profile.getValue();
126 if (mProfile == null)
127 throw new AssertionError();
129 View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
130 final int id = v.getId();
132 boolean wasSyncing = syncingData;
135 final int pos = getAdapterPosition();
136 adapter.updateFocusedItem(pos);
138 case R.id.account_row_acc_name:
139 adapter.noteFocusIsOnAccount(pos);
141 case R.id.account_row_acc_amounts:
142 adapter.noteFocusIsOnAmount(pos);
145 adapter.noteFocusIsOnComment(pos);
150 syncingData = wasSyncing;
154 if (id == R.id.comment) {
155 commentLayout.setAlpha(hasFocus ? 1f : 0.5f);
156 tvComment.setTypeface(null, hasFocus ? Typeface.NORMAL : Typeface.ITALIC);
158 tvComment.setHint(R.string.transaction_account_comment_hint);
160 tvComment.setHint("");
162 if (!hasFocus && Misc.isEmptyOrNull(tvComment.getText()))
163 tvComment.setVisibility(View.INVISIBLE);
167 tvDescription.setOnFocusChangeListener(focusMonitor);
168 tvAccount.setOnFocusChangeListener(focusMonitor);
169 tvAmount.setOnFocusChangeListener(focusMonitor);
170 tvComment.setOnFocusChangeListener(focusMonitor);
172 MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
173 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
174 MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
175 "name", true, this, mProfile);
177 // FIXME: react on configuration (locale) changes
178 decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
179 .getMonetaryDecimalSeparator());
182 final TextWatcher tw = new TextWatcher() {
184 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
188 public void onTextChanged(CharSequence s, int start, int before, int count) {
192 public void afterTextChanged(Editable s) {
193 // debug("input", "text changed");
197 Logger.debug("textWatcher", "calling syncData()");
199 Logger.debug("textWatcher",
200 "syncData() returned, checking if transaction is submittable");
201 adapter.checkTransactionSubmittable();
202 Logger.debug("textWatcher", "done");
205 final TextWatcher amountWatcher = new TextWatcher() {
207 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
209 String.format(Locale.US, "beforeTextChanged: start=%d, count=%d, after=%d",
210 start, count, after));
213 public void onTextChanged(CharSequence s, int start, int before, int count) {}
215 public void afterTextChanged(Editable s) {
216 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
217 // only one decimal separator is allowed
218 // plus and minus are allowed only at the beginning
219 String allowed = "0123456789";
220 String val = s.toString();
221 Logger.debug("input", val);
222 if (val.isEmpty() || (tvAmount.getSelectionStart() == 0))
224 if (!val.contains(decimalSeparator) && !val.contains(decimalDot))
225 allowed += decimalSeparator + decimalDot;
227 tvAmount.setKeyListener(DigitsKeyListener.getInstance(allowed));
231 adapter.checkTransactionSubmittable();
234 tvDescription.addTextChangedListener(tw);
235 tvAccount.addTextChangedListener(tw);
236 tvComment.addTextChangedListener(tw);
237 tvAmount.addTextChangedListener(amountWatcher);
239 tvCurrency.setOnClickListener(v -> {
240 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
241 cpf.showPositionAndPadding();
242 cpf.setOnCurrencySelectedListener(c -> item.setCurrency(c));
243 final AppCompatActivity activity = (AppCompatActivity) v.getContext();
244 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
247 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
248 tvAmount.setKeyListener(
249 DigitsKeyListener.getInstance(Data.locale.getValue(), true, true));
251 tvAmount.setKeyListener(
252 DigitsKeyListener.getInstance("0123456789+-" + decimalSeparator + decimalDot));
254 dateObserver = date -> {
259 tvDate.setText(item.getFormattedDate());
265 descriptionObserver = description -> {
270 tvDescription.setText(description);
276 hintObserver = hint -> {
282 tvAmount.setHint(R.string.zero_amount);
284 tvAmount.setHint(hint);
290 editableObserver = this::setEditable;
291 focusedAccountObserver = index -> {
292 if ((index != null) && index.equals(getAdapterPosition())) {
293 switch (item.getType()) {
295 // bad idea - double pop-up, and not really necessary.
296 // the user can tap the input to get the calendar
297 //if (!tvDate.hasFocus()) tvDate.requestFocus();
298 boolean focused = tvDescription.requestFocus();
299 tvDescription.dismissDropDown();
301 Misc.showSoftKeyboard(
302 (NewTransactionActivity) tvDescription.getContext());
305 // do nothing if a row element already has the focus
306 if (!itemView.hasFocus()) {
307 switch (item.getFocusedElement()) {
309 tvAmount.requestFocus();
312 tvComment.setVisibility(View.VISIBLE);
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);