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 =
352 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
355 currencyPositionObserver =
356 position -> updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
358 showCurrencyObserver = showCurrency -> {
360 tvCurrency.setVisibility(View.VISIBLE);
363 tvCurrency.setVisibility(View.GONE);
364 item.setCurrency(null);
368 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
369 ConstraintLayout.LayoutParams amountLP =
370 (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
371 ConstraintLayout.LayoutParams currencyLP =
372 (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
374 if (position == Currency.Position.before) {
375 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
376 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
378 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
379 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
380 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
381 amountLP.startToEnd = tvCurrency.getId();
383 tvCurrency.setGravity(Gravity.END);
386 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
387 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
389 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
390 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
391 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
392 amountLP.endToStart = tvCurrency.getId();
394 tvCurrency.setGravity(Gravity.START);
397 amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
398 currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
400 tvAmount.setLayoutParams(amountLP);
401 tvCurrency.setLayoutParams(currencyLP);
403 // distance between the amount and the currency symbol
404 int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
406 if (position == Currency.Position.before) {
407 tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
410 tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
413 private void setCurrencyString(String currency) {
414 if ((currency == null) || currency.isEmpty()) {
415 tvCurrency.setText(R.string.currency_symbol);
416 tvCurrency.setTextColor(0x7f000000 + (0x00ffffff & Colors.defaultTextColor));
419 tvCurrency.setText(currency);
420 tvCurrency.setTextColor(Colors.defaultTextColor);
423 private void setCurrency(Currency currency) {
424 setCurrencyString((currency == null) ? null : currency.getName());
426 private void setEditable(Boolean editable) {
427 tvDate.setEnabled(editable);
428 tvDescription.setEnabled(editable);
429 tvAccount.setEnabled(editable);
430 tvAmount.setEnabled(editable);
432 private void setCommentVisible(@NotNull Boolean visible) {
434 // showing; show the comment view and align the comment button to it
435 tvComment.setVisibility(View.VISIBLE);
436 tvComment.requestFocus();
437 ConstraintLayout.LayoutParams lp =
438 (ConstraintLayout.LayoutParams) commentButton.getLayoutParams();
439 lp.bottomToBottom = R.id.comment;
441 commentButton.setLayoutParams(lp);
444 // hiding; hide the comment view and align the comment bottom to the amount
445 tvComment.setVisibility(View.GONE);
446 ConstraintLayout.LayoutParams lp =
447 (ConstraintLayout.LayoutParams) commentButton.getLayoutParams();
448 lp.bottomToBottom = R.id.amount_layout; // R.id.parent doesn't work here
450 commentButton.setLayoutParams(lp);
453 private void setComment(String comment) {
454 if ((comment != null) && !comment.isEmpty())
455 commentButton.setBackgroundResource(R.drawable.ic_comment_black_24dp);
457 commentButton.setBackgroundResource(R.drawable.ic_comment_gray_24dp);
459 private void beginUpdates() {
461 throw new RuntimeException("Already in update mode");
464 private void endUpdates() {
466 throw new RuntimeException("Not in update mode");
472 * Stores the data from the UI elements into the model item
473 * Returns true if there were changes made that suggest transaction has to be
474 * checked for being submittable
476 private boolean syncData() {
481 Logger.debug("new-trans", "skipping syncData() loop");
488 switch (item.getType()) {
490 item.setDate(String.valueOf(tvDate.getText()));
491 item.setDescription(String.valueOf(tvDescription.getText()));
494 final LedgerTransactionAccount account = item.getAccount();
495 account.setAccountName(String.valueOf(tvAccount.getText()));
497 item.setComment(String.valueOf(tvComment.getText()));
499 String amount = String.valueOf(tvAmount.getText());
500 amount = amount.trim();
502 if (amount.isEmpty()) {
503 account.resetAmount();
504 // account.setCurrency(null);
508 amount = amount.replace(decimalSeparator, decimalDot);
509 account.setAmount(Float.parseFloat(amount));
511 catch (NumberFormatException e) {
512 Logger.debug("new-trans", String.format(
513 "assuming amount is not set due to number format exception. " +
514 "input was '%s'", amount));
515 account.resetAmount();
517 final String curr = String.valueOf(tvCurrency.getText());
518 if (curr.equals(tvCurrency.getContext()
520 .getString(R.string.currency_symbol)) ||
522 account.setCurrency(null);
524 account.setCurrency(curr);
529 throw new RuntimeException("Should not happen");
538 private void pickTransactionDate() {
539 DatePickerFragment picker = new DatePickerFragment();
540 picker.setFutureDates(mProfile.getFutureDates());
541 picker.setOnDatePickedListener(this);
542 picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
548 * @param item updates the UI elements with the data from the model item
550 @SuppressLint("DefaultLocale")
551 public void setData(NewTransactionModel.Item item) {
554 if (this.item != null && !this.item.equals(item)) {
555 this.item.stopObservingDate(dateObserver);
556 this.item.stopObservingDescription(descriptionObserver);
557 this.item.stopObservingAmountHint(hintObserver);
558 this.item.stopObservingEditableFlag(editableObserver);
559 this.item.stopObservingCommentVisible(commentVisibleObserver);
560 this.item.stopObservingComment(commentObserver);
562 .stopObservingFocusedItem(focusedAccountObserver);
564 .stopObservingAccountCount(accountCountObserver);
565 Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
566 Data.currencyGap.removeObserver(currencyGapObserver);
567 Data.locale.removeObserver(localeObserver);
568 this.item.stopObservingCurrency(currencyObserver);
569 this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
574 switch (item.getType()) {
576 tvDate.setText(item.getFormattedDate());
577 tvDescription.setText(item.getDescription());
578 lHead.setVisibility(View.VISIBLE);
579 lAccount.setVisibility(View.GONE);
580 lPadding.setVisibility(View.GONE);
584 LedgerTransactionAccount acc = item.getAccount();
585 tvAccount.setText(acc.getAccountName());
586 tvComment.setText(acc.getComment());
587 if (acc.isAmountSet()) {
588 tvAmount.setText(String.format("%1.2f", acc.getAmount()));
591 tvAmount.setText("");
592 // tvAmount.setHint(R.string.zero_amount);
594 tvAmount.setHint(item.getAmountHint());
595 setCurrencyString(acc.getCurrency());
596 lHead.setVisibility(View.GONE);
597 lAccount.setVisibility(View.VISIBLE);
598 lPadding.setVisibility(View.GONE);
602 lHead.setVisibility(View.GONE);
603 lAccount.setVisibility(View.GONE);
604 lPadding.setVisibility(View.VISIBLE);
608 if (this.item == null) { // was null or has changed
610 final NewTransactionActivity activity =
611 (NewTransactionActivity) tvDescription.getContext();
613 if (!item.isOfType(ItemType.bottomFiller)) {
614 item.observeEditableFlag(activity, editableObserver);
616 .observeFocusedItem(activity, focusedAccountObserver);
618 switch (item.getType()) {
620 item.observeDate(activity, dateObserver);
621 item.observeDescription(activity, descriptionObserver);
624 item.observeAmountHint(activity, hintObserver);
625 item.observeCommentVisible(activity, commentVisibleObserver);
626 item.observeComment(activity, commentObserver);
627 Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
628 Data.currencyGap.observe(activity, currencyGapObserver);
629 Data.locale.observe(activity, localeObserver);
630 item.observeCurrency(activity, currencyObserver);
631 item.getModel().showCurrency.observe(activity, showCurrencyObserver);
633 .observeAccountCount(activity, accountCountObserver);
643 public void onDatePicked(int year, int month, int day) {
644 final Calendar c = GregorianCalendar.getInstance();
645 c.set(year, month, day);
646 item.setDate(c.getTime());
647 boolean focused = tvDescription.requestFocus();
649 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
653 public void descriptionSelected(String description) {
654 tvAccount.setText(description);
655 tvAmount.requestFocus(View.FOCUS_FORWARD);