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 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);
112 tvDescription.setNextFocusForwardId(View.NO_ID);
113 tvAccount.setNextFocusForwardId(View.NO_ID);
114 tvAmount.setNextFocusForwardId(View.NO_ID); // magic!
116 tvDate.setOnClickListener(v -> pickTransactionDate());
118 mProfile = Data.profile.getValue();
119 if (mProfile == null)
120 throw new AssertionError();
122 View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
124 boolean wasSyncing = syncingData;
127 final int pos = getAdapterPosition();
128 adapter.updateFocusedItem(pos);
130 case R.id.account_row_acc_name:
131 adapter.noteFocusIsOnAccount(pos);
133 case R.id.account_row_acc_amounts:
134 adapter.noteFocusIsOnAmount(pos);
137 adapter.noteFocusIsOnComment(pos);
142 syncingData = wasSyncing;
147 tvDescription.setOnFocusChangeListener(focusMonitor);
148 tvAccount.setOnFocusChangeListener(focusMonitor);
149 tvAmount.setOnFocusChangeListener(focusMonitor);
151 itemView.findViewById(R.id.comment_button)
152 .setOnClickListener(v -> {
153 final int pos = getAdapterPosition();
154 adapter.toggleComment(pos);
156 MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
157 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
158 MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
159 "name", true, this, mProfile);
161 // FIXME: react on configuration (locale) changes
162 decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
163 .getMonetaryDecimalSeparator());
166 final TextWatcher tw = new TextWatcher() {
168 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
172 public void onTextChanged(CharSequence s, int start, int before, int count) {
176 public void afterTextChanged(Editable s) {
177 // debug("input", "text changed");
181 Logger.debug("textWatcher", "calling syncData()");
183 Logger.debug("textWatcher",
184 "syncData() returned, checking if transaction is submittable");
185 adapter.model.checkTransactionSubmittable(adapter);
186 Logger.debug("textWatcher", "done");
189 final TextWatcher amountWatcher = new TextWatcher() {
191 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
193 String.format(Locale.US, "beforeTextChanged: start=%d, count=%d, after=%d",
194 start, count, after));
197 public void onTextChanged(CharSequence s, int start, int before, int count) {
199 String.format(Locale.US, "onTextChanged: start=%d, before=%d, count=%d",
200 start, before, count));
203 public void afterTextChanged(Editable s) {
204 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
205 // only one decimal separator is allowed
206 // plus and minus are allowed only at the beginning
207 String allowed = "0123456789";
208 String val = s.toString();
209 if (val.isEmpty() || (tvAmount.getSelectionStart() == 0))
211 if (!val.contains(decimalSeparator) && !val.contains(decimalDot))
212 allowed += decimalSeparator + decimalDot;
214 tvAmount.setKeyListener(DigitsKeyListener.getInstance(allowed));
217 adapter.model.checkTransactionSubmittable(adapter);
221 tvDescription.addTextChangedListener(tw);
222 tvAccount.addTextChangedListener(tw);
223 tvComment.addTextChangedListener(tw);
224 tvAmount.addTextChangedListener(amountWatcher);
226 tvCurrency.setOnClickListener(v -> {
227 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
228 cpf.setOnCurrencySelectedListener(this);
229 final AppCompatActivity activity = (AppCompatActivity) v.getContext();
230 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
233 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
234 tvAmount.setKeyListener(
235 DigitsKeyListener.getInstance(Data.locale.getValue(), true, true));
237 tvAmount.setKeyListener(
238 DigitsKeyListener.getInstance("0123456789+-" + decimalSeparator + decimalDot));
240 dateObserver = date -> {
245 tvDate.setText(item.getFormattedDate());
251 descriptionObserver = description -> {
256 tvDescription.setText(description);
262 hintObserver = hint -> {
268 tvAmount.setHint(R.string.zero_amount);
270 tvAmount.setHint(hint);
276 editableObserver = this::setEditable;
277 commentVisibleObserver = this::setCommentVisible;
278 commentObserver = this::setComment;
279 focusedAccountObserver = index -> {
280 if ((index != null) && index.equals(getAdapterPosition())) {
281 switch (item.getType()) {
283 // bad idea - double pop-up, and not really necessary.
284 // the user can tap the input to get the calendar
285 //if (!tvDate.hasFocus()) tvDate.requestFocus();
286 boolean focused = tvDescription.requestFocus();
287 tvDescription.dismissDropDown();
289 Misc.showSoftKeyboard(
290 (NewTransactionActivity) tvDescription.getContext());
293 // do nothing if a row element already has the focus
294 if (!itemView.hasFocus()) {
295 switch (item.getFocusedElement()) {
297 tvAmount.requestFocus();
300 tvComment.requestFocus();
303 focused = tvAccount.requestFocus();
304 tvAccount.dismissDropDown();
306 Misc.showSoftKeyboard(
307 (NewTransactionActivity) tvAccount.getContext());
316 accountCountObserver = count -> {
317 final int adapterPosition = getAdapterPosition();
318 final int layoutPosition = getLayoutPosition();
319 Logger.debug("holder",
320 String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
321 adapterPosition, layoutPosition, item.getType()
323 .concat(item.getType() ==
324 ItemType.transactionRow
325 ? String.format(Locale.US,
331 ? String.format(Locale.US,
336 if (adapterPosition == count)
337 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
339 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
342 currencyPositionObserver = position -> {
343 updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
346 currencyGapObserver = hasGap -> {
347 updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(), hasGap);
350 localeObserver = locale -> {
351 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
352 tvAmount.setKeyListener(DigitsKeyListener.getInstance(locale, true, true));
355 currencyObserver = this::setCurrency;
357 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
358 ConstraintLayout.LayoutParams amountLP =
359 (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
360 ConstraintLayout.LayoutParams currencyLP =
361 (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
363 if (position == Currency.Position.before) {
364 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
365 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
367 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
368 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
369 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
370 amountLP.startToEnd = tvCurrency.getId();
372 tvCurrency.setGravity(Gravity.END);
375 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
376 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
378 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
379 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
380 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
381 amountLP.endToStart = tvCurrency.getId();
383 tvCurrency.setGravity(Gravity.START);
386 amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
387 currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
389 tvAmount.setLayoutParams(amountLP);
390 tvCurrency.setLayoutParams(currencyLP);
392 // distance between the amount and the currency symbol
393 int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
395 if (position == Currency.Position.before) {
396 tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
399 tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
402 private void setCurrencyString(String currency) {
403 if ((currency == null) || currency.isEmpty()) {
404 tvCurrency.setText(R.string.currency_symbol);
405 tvCurrency.setTextColor(0x7f000000 + (0x00ffffff & Colors.defaultTextColor));
408 tvCurrency.setText(currency);
409 tvCurrency.setTextColor(Colors.defaultTextColor);
412 private void setCurrency(Currency currency) {
413 setCurrencyString((currency == null) ? null : currency.getName());
415 private void setEditable(Boolean editable) {
416 tvDate.setEnabled(editable);
417 tvDescription.setEnabled(editable);
418 tvAccount.setEnabled(editable);
419 tvAmount.setEnabled(editable);
421 private void setCommentVisible(Boolean visible) {
423 // showing; show the comment view and align the comment button to it
424 tvComment.setVisibility(View.VISIBLE);
425 tvComment.requestFocus();
426 ConstraintLayout.LayoutParams lp =
427 (ConstraintLayout.LayoutParams) commentButton.getLayoutParams();
428 lp.bottomToBottom = R.id.comment;
430 commentButton.setLayoutParams(lp);
433 // hiding; hide the comment comment view and align amounts layout under it
434 tvComment.setVisibility(View.GONE);
435 ConstraintLayout.LayoutParams lp =
436 (ConstraintLayout.LayoutParams) commentButton.getLayoutParams();
437 lp.bottomToBottom = R.id.ntr_account; // R.id.parent doesn't work here
439 commentButton.setLayoutParams(lp);
442 private void setComment(String comment) {
443 if ((comment != null) && !comment.isEmpty())
444 commentButton.setBackgroundResource(R.drawable.ic_comment_black_24dp);
446 commentButton.setBackgroundResource(R.drawable.ic_comment_gray_24dp);
448 private void beginUpdates() {
450 throw new RuntimeException("Already in update mode");
453 private void endUpdates() {
455 throw new RuntimeException("Not in update mode");
461 * Stores the data from the UI elements into the model item
463 private void syncData() {
468 Logger.debug("new-trans", "skipping syncData() loop");
475 switch (item.getType()) {
477 item.setDate(String.valueOf(tvDate.getText()));
478 item.setDescription(String.valueOf(tvDescription.getText()));
481 final LedgerTransactionAccount account = item.getAccount();
482 account.setAccountName(String.valueOf(tvAccount.getText()));
484 item.setComment(String.valueOf(tvComment.getText()));
486 // TODO: handle multiple amounts
487 String amount = String.valueOf(tvAmount.getText());
488 amount = amount.trim();
490 if (amount.isEmpty()) {
491 account.resetAmount();
492 account.setCurrency(null);
496 amount = amount.replace(decimalSeparator, decimalDot);
497 account.setAmount(Float.parseFloat(amount));
499 catch (NumberFormatException e) {
500 Logger.debug("new-trans", String.format(
501 "assuming amount is not set due to number format exception. " +
502 "input was '%s'", amount));
503 account.resetAmount();
505 final String curr = String.valueOf(tvCurrency.getText());
506 if (curr.equals(tvCurrency.getContext()
508 .getString(R.string.currency_symbol)) ||
510 account.setCurrency(null);
512 account.setCurrency(curr);
517 throw new RuntimeException("Should not happen");
524 private void pickTransactionDate() {
525 DatePickerFragment picker = new DatePickerFragment();
526 picker.setFutureDates(mProfile.getFutureDates());
527 picker.setOnDatePickedListener(this);
528 picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
534 * @param item updates the UI elements with the data from the model item
536 @SuppressLint("DefaultLocale")
537 public void setData(NewTransactionModel.Item item) {
540 if (this.item != null && !this.item.equals(item)) {
541 this.item.stopObservingDate(dateObserver);
542 this.item.stopObservingDescription(descriptionObserver);
543 this.item.stopObservingAmountHint(hintObserver);
544 this.item.stopObservingEditableFlag(editableObserver);
545 this.item.stopObservingCommentVisible(commentVisibleObserver);
546 this.item.stopObservingComment(commentObserver);
548 .stopObservingFocusedItem(focusedAccountObserver);
550 .stopObservingAccountCount(accountCountObserver);
551 Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
552 Data.currencyGap.removeObserver(currencyGapObserver);
553 Data.locale.removeObserver(localeObserver);
554 this.item.stopObservingCurrency(currencyObserver);
559 switch (item.getType()) {
561 tvDate.setText(item.getFormattedDate());
562 tvDescription.setText(item.getDescription());
563 lHead.setVisibility(View.VISIBLE);
564 lAccount.setVisibility(View.GONE);
565 lPadding.setVisibility(View.GONE);
569 LedgerTransactionAccount acc = item.getAccount();
570 tvAccount.setText(acc.getAccountName());
571 tvComment.setText(acc.getComment());
572 if (acc.isAmountSet()) {
573 tvAmount.setText(String.format("%1.2f", acc.getAmount()));
576 tvAmount.setText("");
577 // tvAmount.setHint(R.string.zero_amount);
579 tvAmount.setHint(item.getAmountHint());
580 setCurrencyString(acc.getCurrency());
581 lHead.setVisibility(View.GONE);
582 lAccount.setVisibility(View.VISIBLE);
583 lPadding.setVisibility(View.GONE);
587 lHead.setVisibility(View.GONE);
588 lAccount.setVisibility(View.GONE);
589 lPadding.setVisibility(View.VISIBLE);
594 if (this.item == null) { // was null or has changed
596 final NewTransactionActivity activity =
597 (NewTransactionActivity) tvDescription.getContext();
598 item.observeDate(activity, dateObserver);
599 item.observeDescription(activity, descriptionObserver);
600 item.observeAmountHint(activity, hintObserver);
601 item.observeEditableFlag(activity, editableObserver);
602 item.observeCommentVisible(activity, commentVisibleObserver);
603 item.observeComment(activity, commentObserver);
605 .observeFocusedItem(activity, focusedAccountObserver);
607 .observeAccountCount(activity, accountCountObserver);
608 Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
609 Data.currencyGap.observe(activity, currencyGapObserver);
610 Data.locale.observe(activity, localeObserver);
611 item.observeCurrency(activity, currencyObserver);
619 public void onDatePicked(int year, int month, int day) {
620 final Calendar c = GregorianCalendar.getInstance();
621 c.set(year, month, day);
622 item.setDate(c.getTime());
623 boolean focused = tvDescription.requestFocus();
625 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
629 public void onCurrencySelected(Currency item) {
630 this.item.setCurrency(item);
633 public void descriptionSelected(String description) {
634 tvAccount.setText(description);
635 tvAmount.requestFocus(View.FOCUS_FORWARD);