2 * Copyright © 2021 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.new_transaction;
20 import android.annotation.SuppressLint;
21 import android.graphics.Typeface;
22 import android.text.Editable;
23 import android.text.TextUtils;
24 import android.text.TextWatcher;
25 import android.view.Gravity;
26 import android.view.View;
27 import android.view.inputmethod.EditorInfo;
28 import android.widget.EditText;
29 import android.widget.TextView;
31 import androidx.annotation.ColorInt;
32 import androidx.annotation.NonNull;
33 import androidx.constraintlayout.widget.ConstraintLayout;
34 import androidx.recyclerview.widget.RecyclerView;
36 import net.ktnx.mobileledger.R;
37 import net.ktnx.mobileledger.databinding.NewTransactionAccountRowBinding;
38 import net.ktnx.mobileledger.db.AccountAutocompleteAdapter;
39 import net.ktnx.mobileledger.model.Currency;
40 import net.ktnx.mobileledger.model.Data;
41 import net.ktnx.mobileledger.ui.CurrencySelectorFragment;
42 import net.ktnx.mobileledger.ui.TextViewClearHelper;
43 import net.ktnx.mobileledger.utils.DimensionUtils;
44 import net.ktnx.mobileledger.utils.Logger;
45 import net.ktnx.mobileledger.utils.Misc;
47 import java.text.DecimalFormatSymbols;
49 class NewTransactionAccountRowItemHolder extends NewTransactionItemViewHolder {
50 private final String decimalDot = ".";
51 private final NewTransactionAccountRowBinding b;
52 private boolean ignoreFocusChanges = false;
53 private String decimalSeparator;
54 private boolean inUpdate = false;
55 private boolean syncingData = false;
56 NewTransactionAccountRowItemHolder(@NonNull NewTransactionAccountRowBinding b,
57 NewTransactionItemsAdapter adapter) {
60 new TextViewClearHelper().attachToTextView(b.comment);
62 b.accountRowAccName.setNextFocusForwardId(View.NO_ID);
63 b.accountRowAccAmounts.setNextFocusForwardId(View.NO_ID); // magic!
65 b.accountCommentButton.setOnClickListener(v -> {
66 b.comment.setVisibility(View.VISIBLE);
67 b.comment.requestFocus();
70 @SuppressLint("DefaultLocale") View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
71 final int id = v.getId();
73 boolean wasSyncing = syncingData;
76 final int pos = getBindingAdapterPosition();
77 if (id == R.id.account_row_acc_name) {
78 adapter.noteFocusIsOnAccount(pos);
80 else if (id == R.id.account_row_acc_amounts) {
81 adapter.noteFocusIsOnAmount(pos);
83 else if (id == R.id.comment) {
84 adapter.noteFocusIsOnComment(pos);
87 throw new IllegalStateException("Where is the focus? " + id);
90 syncingData = wasSyncing;
94 if (id == R.id.account_row_acc_amounts) {
96 String input = String.valueOf(b.accountRowAccAmounts.getText());
97 input = input.replace(decimalSeparator, decimalDot);
98 final String newText = String.format("%4.2f", Float.parseFloat(input));
99 if (!newText.equals(input)) {
100 boolean wasSyncingData = syncingData;
103 b.accountRowAccAmounts.setText(newText);
106 syncingData = wasSyncingData;
110 catch (NumberFormatException ex) {
116 if (id == R.id.comment) {
117 commentFocusChanged(b.comment, hasFocus);
121 b.accountRowAccName.setOnFocusChangeListener(focusMonitor);
122 b.accountRowAccAmounts.setOnFocusChangeListener(focusMonitor);
123 b.comment.setOnFocusChangeListener(focusMonitor);
125 NewTransactionActivity activity = (NewTransactionActivity) b.getRoot()
128 b.accountRowAccName.setAdapter(new AccountAutocompleteAdapter(b.getRoot()
129 .getContext(), mProfile));
131 decimalSeparator = "";
132 Data.locale.observe(activity, locale -> decimalSeparator = String.valueOf(
133 DecimalFormatSymbols.getInstance(locale)
134 .getMonetaryDecimalSeparator()));
136 final TextWatcher tw = new TextWatcher() {
138 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
142 public void onTextChanged(CharSequence s, int start, int before, int count) {
146 public void afterTextChanged(Editable s) {
147 // debug("input", "text changed");
151 Logger.debug("textWatcher", "calling syncData()");
153 Logger.debug("textWatcher",
154 "syncData() returned, checking if transaction is submittable");
155 adapter.model.checkTransactionSubmittable(null);
157 Logger.debug("textWatcher", "done");
160 final TextWatcher amountWatcher = new TextWatcher() {
162 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
164 public void onTextChanged(CharSequence s, int start, int before, int count) {}
166 public void afterTextChanged(Editable s) {
167 checkAmountValid(s.toString());
170 adapter.model.checkTransactionSubmittable(null);
173 b.accountRowAccName.addTextChangedListener(tw);
174 monitorComment(b.comment);
175 b.accountRowAccAmounts.addTextChangedListener(amountWatcher);
177 b.currencyButton.setOnClickListener(v -> {
178 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
179 cpf.showPositionAndPadding();
180 cpf.setOnCurrencySelectedListener(
181 c -> adapter.setItemCurrency(getBindingAdapterPosition(), c));
182 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
185 commentFocusChanged(b.comment, false);
187 adapter.model.getFocusInfo()
188 .observe(activity, this::applyFocus);
190 Data.currencyGap.observe(activity,
191 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
194 Data.currencySymbolPosition.observe(activity,
195 position -> updateCurrencyPositionAndPadding(position,
196 Data.currencyGap.getValue()));
198 adapter.model.getShowCurrency()
199 .observe(activity, showCurrency -> {
201 b.currency.setVisibility(View.VISIBLE);
202 b.currencyButton.setVisibility(View.VISIBLE);
203 setCurrencyString(mProfile.getDefaultCommodity());
206 b.currency.setVisibility(View.GONE);
207 b.currencyButton.setVisibility(View.GONE);
208 setCurrencyString(null);
212 adapter.model.getShowComments()
213 .observe(activity, show -> b.commentLayout.setVisibility(
214 show ? View.VISIBLE : View.GONE));
216 private void applyFocus(NewTransactionModel.FocusInfo focusInfo) {
217 if (ignoreFocusChanges) {
218 Logger.debug("new-trans", "Ignoring focus change");
221 ignoreFocusChanges = true;
223 if (((focusInfo == null) || (focusInfo.element == null) ||
224 focusInfo.position != getBindingAdapterPosition()))
227 final NewTransactionModel.Item item = getItem();
231 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
232 switch (focusInfo.element) {
234 b.accountRowAccAmounts.requestFocus();
237 b.comment.setVisibility(View.VISIBLE);
238 b.comment.requestFocus();
241 boolean focused = b.accountRowAccName.requestFocus();
242 // b.accountRowAccName.dismissDropDown();
244 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
250 ignoreFocusChanges = false;
253 public void checkAmountValid(String s) {
254 boolean valid = true;
256 if (s.length() > 0) {
257 float ignored = Float.parseFloat(s.replace(decimalSeparator, decimalDot));
260 catch (NumberFormatException ex) {
264 displayAmountValidity(valid);
266 private void displayAmountValidity(boolean valid) {
267 b.accountRowAccAmounts.setCompoundDrawablesRelativeWithIntrinsicBounds(
268 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
269 b.accountRowAccAmounts.setMinEms(valid ? 4 : 5);
271 private void monitorComment(EditText editText) {
272 editText.addTextChangedListener(new TextWatcher() {
274 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
277 public void onTextChanged(CharSequence s, int start, int before, int count) {
280 public void afterTextChanged(Editable s) {
281 // debug("input", "text changed");
285 Logger.debug("textWatcher", "calling syncData()");
287 Logger.debug("textWatcher",
288 "syncData() returned, checking if transaction is submittable");
289 styleComment(editText, s.toString());
290 Logger.debug("textWatcher", "done");
294 private void commentFocusChanged(TextView textView, boolean hasFocus) {
295 @ColorInt int textColor;
296 textColor = b.dummyText.getTextColors()
299 textView.setTypeface(null, Typeface.NORMAL);
300 textView.setHint(R.string.transaction_account_comment_hint);
303 int alpha = (textColor >> 24 & 0xff);
304 alpha = 3 * alpha / 4;
305 textColor = (alpha << 24) | (0x00ffffff & textColor);
306 textView.setTypeface(null, Typeface.ITALIC);
307 textView.setHint("");
308 if (TextUtils.isEmpty(textView.getText())) {
309 textView.setVisibility(View.INVISIBLE);
312 textView.setTextColor(textColor);
315 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
316 ConstraintLayout.LayoutParams amountLP =
317 (ConstraintLayout.LayoutParams) b.accountRowAccAmounts.getLayoutParams();
318 ConstraintLayout.LayoutParams currencyLP =
319 (ConstraintLayout.LayoutParams) b.currency.getLayoutParams();
321 if (position == Currency.Position.before) {
322 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
323 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
325 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
326 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
327 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
328 amountLP.startToEnd = b.currency.getId();
330 b.currency.setGravity(Gravity.END);
333 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
334 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
336 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
337 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
338 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
339 amountLP.endToStart = b.currency.getId();
341 b.currency.setGravity(Gravity.START);
344 amountLP.resolveLayoutDirection(b.accountRowAccAmounts.getLayoutDirection());
345 currencyLP.resolveLayoutDirection(b.currency.getLayoutDirection());
347 b.accountRowAccAmounts.setLayoutParams(amountLP);
348 b.currency.setLayoutParams(currencyLP);
350 // distance between the amount and the currency symbol
351 int gapSize = DimensionUtils.sp2px(b.currency.getContext(), 5);
353 if (position == Currency.Position.before) {
354 b.currency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
357 b.currency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
360 private void setCurrencyString(String currency) {
361 @ColorInt int textColor = b.dummyText.getTextColors()
363 if (TextUtils.isEmpty(currency)) {
364 b.currency.setText(R.string.currency_symbol);
365 int alpha = (textColor >> 24) & 0xff;
366 alpha = alpha * 3 / 4;
367 b.currency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
370 b.currency.setText(currency);
371 b.currency.setTextColor(textColor);
374 private void setCurrency(Currency currency) {
375 setCurrencyString((currency == null) ? null : currency.getName());
377 private void setEditable(Boolean editable) {
378 b.accountRowAccName.setEnabled(editable);
379 b.accountRowAccAmounts.setEnabled(editable);
381 private void beginUpdates() {
383 throw new RuntimeException("Already in update mode");
386 private void endUpdates() {
388 throw new RuntimeException("Not in update mode");
394 * Stores the data from the UI elements into the model item
395 * Returns true if there were changes made that suggest transaction has to be
396 * checked for being submittable
398 private boolean syncData() {
400 Logger.debug("new-trans", "skipping syncData() loop");
404 if (getBindingAdapterPosition() == RecyclerView.NO_POSITION) {
405 // probably the row was swiped out
406 Logger.debug("new-trans", "Ignoring request to suncData(): adapter position negative");
410 final NewTransactionModel.Item item = getItem();
416 boolean significantChange = false;
419 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
421 // having account name is important
422 final Editable incomingAccountName = b.accountRowAccName.getText();
423 if (TextUtils.isEmpty(acc.getAccountName()) != TextUtils.isEmpty(incomingAccountName))
424 significantChange = true;
426 acc.setAccountName(String.valueOf(incomingAccountName));
427 final int accNameSelEnd = b.accountRowAccName.getSelectionEnd();
428 final int accNameSelStart = b.accountRowAccName.getSelectionStart();
429 acc.setAccountNameCursorPosition(accNameSelEnd);
431 acc.setComment(String.valueOf(b.comment.getText()));
433 String amount = String.valueOf(b.accountRowAccAmounts.getText());
434 amount = amount.trim();
436 if (amount.isEmpty()) {
437 if (acc.isAmountSet())
438 significantChange = true;
440 acc.setAmountValid(true);
444 amount = amount.replace(decimalSeparator, decimalDot);
445 final float parsedAmount = Float.parseFloat(amount);
446 if (!acc.isAmountSet() || !Misc.equalFloats(parsedAmount, acc.getAmount()))
447 significantChange = true;
448 acc.setAmount(parsedAmount);
449 acc.setAmountValid(true);
451 catch (NumberFormatException e) {
452 Logger.debug("new-trans", String.format(
453 "assuming amount is not set due to number format exception. " +
454 "input was '%s'", amount));
455 if (acc.isAmountValid())
456 significantChange = true;
457 acc.setAmountValid(false);
459 final String curr = String.valueOf(b.currency.getText());
460 final String currValue;
461 if (curr.equals(b.currency.getContext()
463 .getString(R.string.currency_symbol)) || curr.isEmpty())
468 if (!significantChange && !Misc.equalStrings(acc.getCurrency(), currValue))
469 significantChange = true;
470 acc.setCurrency(currValue);
473 return significantChange;
482 * @param item updates the UI elements with the data from the model item
484 @SuppressLint("DefaultLocale")
485 public void bind(@NonNull NewTransactionModel.Item item) {
490 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
492 final String incomingAccountName = acc.getAccountName();
493 final String presentAccountName = String.valueOf(b.accountRowAccName.getText());
494 if (!Misc.equalStrings(incomingAccountName, presentAccountName)) {
496 String.format("Setting account name from '%s' to '%s' (| @ %d)",
497 presentAccountName, incomingAccountName,
498 acc.getAccountNameCursorPosition()));
499 // avoid triggering completion pop-up
500 AccountAutocompleteAdapter a =
501 (AccountAutocompleteAdapter) b.accountRowAccName.getAdapter();
503 b.accountRowAccName.setAdapter(null);
504 b.accountRowAccName.setText(incomingAccountName);
505 b.accountRowAccName.setSelection(acc.getAccountNameCursorPosition());
508 b.accountRowAccName.setAdapter(a);
512 final String amountHint = acc.getAmountHint();
513 if (amountHint == null) {
514 b.accountRowAccAmounts.setHint(R.string.zero_amount);
517 b.accountRowAccAmounts.setHint(amountHint);
520 b.accountRowAccAmounts.setImeOptions(
521 acc.isLast() ? EditorInfo.IME_ACTION_DONE : EditorInfo.IME_ACTION_NEXT);
523 setCurrencyString(acc.getCurrency());
524 b.accountRowAccAmounts.setText(
525 acc.isAmountSet() ? String.format("%4.2f", acc.getAmount()) : null);
526 displayAmountValidity(true);
528 final String comment = acc.getComment();
529 b.comment.setText(comment);
530 styleComment(b.comment, comment);
534 NewTransactionItemsAdapter adapter =
535 (NewTransactionItemsAdapter) getBindingAdapter();
537 applyFocus(adapter.model.getFocusInfo()
548 private void styleComment(EditText editText, String comment) {
549 final View focusedView = editText.findFocus();
550 editText.setTypeface(null, (focusedView == editText) ? Typeface.NORMAL : Typeface.ITALIC);
551 editText.setVisibility(
552 ((focusedView != editText) && TextUtils.isEmpty(comment)) ? View.INVISIBLE