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.OnCurrencySelectedListener;
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 java.text.DecimalFormatSymbols;
58 import java.util.Calendar;
59 import java.util.Date;
60 import java.util.GregorianCalendar;
61 import java.util.Locale;
63 import static net.ktnx.mobileledger.ui.activity.NewTransactionModel.ItemType;
65 class NewTransactionItemHolder extends RecyclerView.ViewHolder
66 implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback,
67 OnCurrencySelectedListener {
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.model.checkTransactionSubmittable(adapter);
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 String.format(Locale.US, "onTextChanged: start=%d, before=%d, count=%d",
201 start, before, count));
204 public void afterTextChanged(Editable s) {
205 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
206 // only one decimal separator is allowed
207 // plus and minus are allowed only at the beginning
208 String allowed = "0123456789";
209 String val = s.toString();
210 if (val.isEmpty() || (tvAmount.getSelectionStart() == 0))
212 if (!val.contains(decimalSeparator) && !val.contains(decimalDot))
213 allowed += decimalSeparator + decimalDot;
215 tvAmount.setKeyListener(DigitsKeyListener.getInstance(allowed));
218 adapter.model.checkTransactionSubmittable(adapter);
222 tvDescription.addTextChangedListener(tw);
223 tvAccount.addTextChangedListener(tw);
224 tvComment.addTextChangedListener(tw);
225 tvAmount.addTextChangedListener(amountWatcher);
227 tvCurrency.setOnClickListener(v -> {
228 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
229 cpf.setOnCurrencySelectedListener(this);
230 final AppCompatActivity activity = (AppCompatActivity) v.getContext();
231 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
234 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
235 tvAmount.setKeyListener(
236 DigitsKeyListener.getInstance(Data.locale.getValue(), true, true));
238 tvAmount.setKeyListener(
239 DigitsKeyListener.getInstance("0123456789+-" + decimalSeparator + decimalDot));
241 dateObserver = date -> {
246 tvDate.setText(item.getFormattedDate());
252 descriptionObserver = description -> {
257 tvDescription.setText(description);
263 hintObserver = hint -> {
269 tvAmount.setHint(R.string.zero_amount);
271 tvAmount.setHint(hint);
277 editableObserver = this::setEditable;
278 commentVisibleObserver = this::setCommentVisible;
279 commentObserver = this::setComment;
280 focusedAccountObserver = index -> {
281 if ((index != null) && index.equals(getAdapterPosition())) {
282 switch (item.getType()) {
284 // bad idea - double pop-up, and not really necessary.
285 // the user can tap the input to get the calendar
286 //if (!tvDate.hasFocus()) tvDate.requestFocus();
287 boolean focused = tvDescription.requestFocus();
288 tvDescription.dismissDropDown();
290 Misc.showSoftKeyboard(
291 (NewTransactionActivity) tvDescription.getContext());
294 // do nothing if a row element already has the focus
295 if (!itemView.hasFocus()) {
296 switch (item.getFocusedElement()) {
298 tvAmount.requestFocus();
301 tvComment.requestFocus();
304 focused = tvAccount.requestFocus();
305 tvAccount.dismissDropDown();
307 Misc.showSoftKeyboard(
308 (NewTransactionActivity) tvAccount.getContext());
317 accountCountObserver = count -> {
318 final int adapterPosition = getAdapterPosition();
319 final int layoutPosition = getLayoutPosition();
320 Logger.debug("holder",
321 String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
322 adapterPosition, layoutPosition, item.getType()
324 .concat(item.getType() ==
325 ItemType.transactionRow
326 ? String.format(Locale.US,
332 ? String.format(Locale.US,
337 if (adapterPosition == count)
338 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
340 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
343 currencyPositionObserver = position -> {
344 updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
347 currencyGapObserver = hasGap -> {
348 updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(), hasGap);
351 localeObserver = locale -> {
352 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
353 tvAmount.setKeyListener(DigitsKeyListener.getInstance(locale, true, true));
356 currencyObserver = currency -> {
357 setCurrency(currency);
358 adapter.model.checkTransactionSubmittable(adapter);
361 showCurrencyObserver = showCurrency -> {
362 if (item.getType() == ItemType.transactionRow) {
364 tvCurrency.setVisibility(View.VISIBLE);
367 tvCurrency.setVisibility(View.GONE);
368 item.setCurrency(null);
373 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
374 ConstraintLayout.LayoutParams amountLP =
375 (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
376 ConstraintLayout.LayoutParams currencyLP =
377 (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
379 if (position == Currency.Position.before) {
380 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
381 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
383 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
384 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
385 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
386 amountLP.startToEnd = tvCurrency.getId();
388 tvCurrency.setGravity(Gravity.END);
391 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
392 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
394 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
395 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
396 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
397 amountLP.endToStart = tvCurrency.getId();
399 tvCurrency.setGravity(Gravity.START);
402 amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
403 currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
405 tvAmount.setLayoutParams(amountLP);
406 tvCurrency.setLayoutParams(currencyLP);
408 // distance between the amount and the currency symbol
409 int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
411 if (position == Currency.Position.before) {
412 tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
415 tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
418 private void setCurrencyString(String currency) {
419 if ((currency == null) || currency.isEmpty()) {
420 tvCurrency.setText(R.string.currency_symbol);
421 tvCurrency.setTextColor(0x7f000000 + (0x00ffffff & Colors.defaultTextColor));
424 tvCurrency.setText(currency);
425 tvCurrency.setTextColor(Colors.defaultTextColor);
428 private void setCurrency(Currency currency) {
429 setCurrencyString((currency == null) ? null : currency.getName());
431 private void setEditable(Boolean editable) {
432 tvDate.setEnabled(editable);
433 tvDescription.setEnabled(editable);
434 tvAccount.setEnabled(editable);
435 tvAmount.setEnabled(editable);
437 private void setCommentVisible(Boolean visible) {
439 // showing; show the comment view and align the comment button to it
440 tvComment.setVisibility(View.VISIBLE);
441 tvComment.requestFocus();
442 ConstraintLayout.LayoutParams lp =
443 (ConstraintLayout.LayoutParams) commentButton.getLayoutParams();
444 lp.bottomToBottom = R.id.comment;
446 commentButton.setLayoutParams(lp);
449 // hiding; hide the comment comment view and align amounts layout under it
450 tvComment.setVisibility(View.GONE);
451 ConstraintLayout.LayoutParams lp =
452 (ConstraintLayout.LayoutParams) commentButton.getLayoutParams();
453 lp.bottomToBottom = R.id.ntr_account; // R.id.parent doesn't work here
455 commentButton.setLayoutParams(lp);
458 private void setComment(String comment) {
459 if ((comment != null) && !comment.isEmpty())
460 commentButton.setBackgroundResource(R.drawable.ic_comment_black_24dp);
462 commentButton.setBackgroundResource(R.drawable.ic_comment_gray_24dp);
464 private void beginUpdates() {
466 throw new RuntimeException("Already in update mode");
469 private void endUpdates() {
471 throw new RuntimeException("Not in update mode");
477 * Stores the data from the UI elements into the model item
479 private void syncData() {
484 Logger.debug("new-trans", "skipping syncData() loop");
491 switch (item.getType()) {
493 item.setDate(String.valueOf(tvDate.getText()));
494 item.setDescription(String.valueOf(tvDescription.getText()));
497 final LedgerTransactionAccount account = item.getAccount();
498 account.setAccountName(String.valueOf(tvAccount.getText()));
500 item.setComment(String.valueOf(tvComment.getText()));
502 // TODO: handle multiple amounts
503 String amount = String.valueOf(tvAmount.getText());
504 amount = amount.trim();
506 if (amount.isEmpty()) {
507 account.resetAmount();
508 // account.setCurrency(null);
512 amount = amount.replace(decimalSeparator, decimalDot);
513 account.setAmount(Float.parseFloat(amount));
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 account.resetAmount();
521 final String curr = String.valueOf(tvCurrency.getText());
522 if (curr.equals(tvCurrency.getContext()
524 .getString(R.string.currency_symbol)) ||
526 account.setCurrency(null);
528 account.setCurrency(curr);
533 throw new RuntimeException("Should not happen");
540 private void pickTransactionDate() {
541 DatePickerFragment picker = new DatePickerFragment();
542 picker.setFutureDates(mProfile.getFutureDates());
543 picker.setOnDatePickedListener(this);
544 picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
550 * @param item updates the UI elements with the data from the model item
552 @SuppressLint("DefaultLocale")
553 public void setData(NewTransactionModel.Item item) {
556 if (this.item != null && !this.item.equals(item)) {
557 this.item.stopObservingDate(dateObserver);
558 this.item.stopObservingDescription(descriptionObserver);
559 this.item.stopObservingAmountHint(hintObserver);
560 this.item.stopObservingEditableFlag(editableObserver);
561 this.item.stopObservingCommentVisible(commentVisibleObserver);
562 this.item.stopObservingComment(commentObserver);
564 .stopObservingFocusedItem(focusedAccountObserver);
566 .stopObservingAccountCount(accountCountObserver);
567 Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
568 Data.currencyGap.removeObserver(currencyGapObserver);
569 Data.locale.removeObserver(localeObserver);
570 this.item.stopObservingCurrency(currencyObserver);
571 this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
576 switch (item.getType()) {
578 tvDate.setText(item.getFormattedDate());
579 tvDescription.setText(item.getDescription());
580 lHead.setVisibility(View.VISIBLE);
581 lAccount.setVisibility(View.GONE);
582 lPadding.setVisibility(View.GONE);
586 LedgerTransactionAccount acc = item.getAccount();
587 tvAccount.setText(acc.getAccountName());
588 tvComment.setText(acc.getComment());
589 if (acc.isAmountSet()) {
590 tvAmount.setText(String.format("%1.2f", acc.getAmount()));
593 tvAmount.setText("");
594 // tvAmount.setHint(R.string.zero_amount);
596 tvAmount.setHint(item.getAmountHint());
597 setCurrencyString(acc.getCurrency());
598 lHead.setVisibility(View.GONE);
599 lAccount.setVisibility(View.VISIBLE);
600 lPadding.setVisibility(View.GONE);
604 lHead.setVisibility(View.GONE);
605 lAccount.setVisibility(View.GONE);
606 lPadding.setVisibility(View.VISIBLE);
611 if (this.item == null) { // was null or has changed
613 final NewTransactionActivity activity =
614 (NewTransactionActivity) tvDescription.getContext();
615 item.observeDate(activity, dateObserver);
616 item.observeDescription(activity, descriptionObserver);
617 item.observeAmountHint(activity, hintObserver);
618 item.observeEditableFlag(activity, editableObserver);
619 item.observeCommentVisible(activity, commentVisibleObserver);
620 item.observeComment(activity, commentObserver);
622 .observeFocusedItem(activity, focusedAccountObserver);
624 .observeAccountCount(activity, accountCountObserver);
625 Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
626 Data.currencyGap.observe(activity, currencyGapObserver);
627 Data.locale.observe(activity, localeObserver);
628 item.observeCurrency(activity, currencyObserver);
629 item.getModel().showCurrency.observe(activity, showCurrencyObserver);
637 public void onDatePicked(int year, int month, int day) {
638 final Calendar c = GregorianCalendar.getInstance();
639 c.set(year, month, day);
640 item.setDate(c.getTime());
641 boolean focused = tvDescription.requestFocus();
643 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
647 public void onCurrencySelected(Currency item) {
648 this.item.setCurrency(item);
651 public void descriptionSelected(String description) {
652 tvAccount.setText(description);
653 tvAmount.requestFocus(View.FOCUS_FORWARD);