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.AccountWithAmountsAutocompleteAdapter;
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 AccountWithAmountsAutocompleteAdapter(b.getRoot()
132 decimalSeparator = "";
133 Data.locale.observe(activity, locale -> decimalSeparator = String.valueOf(
134 DecimalFormatSymbols.getInstance(locale)
135 .getMonetaryDecimalSeparator()));
137 final TextWatcher tw = new TextWatcher() {
139 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
143 public void onTextChanged(CharSequence s, int start, int before, int count) {
147 public void afterTextChanged(Editable s) {
148 // debug("input", "text changed");
152 Logger.debug("textWatcher", "calling syncData()");
154 Logger.debug("textWatcher",
155 "syncData() returned, checking if transaction is submittable");
156 adapter.model.checkTransactionSubmittable(null);
158 Logger.debug("textWatcher", "done");
161 final TextWatcher amountWatcher = new TextWatcher() {
163 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
165 public void onTextChanged(CharSequence s, int start, int before, int count) {}
167 public void afterTextChanged(Editable s) {
168 checkAmountValid(s.toString());
171 adapter.model.checkTransactionSubmittable(null);
174 b.accountRowAccName.addTextChangedListener(tw);
175 monitorComment(b.comment);
176 b.accountRowAccAmounts.addTextChangedListener(amountWatcher);
178 b.currencyButton.setOnClickListener(v -> {
179 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
180 cpf.showPositionAndPadding();
181 cpf.setOnCurrencySelectedListener(
182 c -> adapter.setItemCurrency(getBindingAdapterPosition(), c));
183 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
186 commentFocusChanged(b.comment, false);
188 adapter.model.getFocusInfo()
189 .observe(activity, this::applyFocus);
191 Data.currencyGap.observe(activity,
192 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
195 Data.currencySymbolPosition.observe(activity,
196 position -> updateCurrencyPositionAndPadding(position,
197 Data.currencyGap.getValue()));
199 adapter.model.getShowCurrency()
200 .observe(activity, showCurrency -> {
202 b.currency.setVisibility(View.VISIBLE);
203 b.currencyButton.setVisibility(View.VISIBLE);
204 setCurrencyString(mProfile.getDefaultCommodity());
207 b.currency.setVisibility(View.GONE);
208 b.currencyButton.setVisibility(View.GONE);
209 setCurrencyString(null);
213 adapter.model.getShowComments()
214 .observe(activity, show -> b.commentLayout.setVisibility(
215 show ? View.VISIBLE : View.GONE));
217 private void applyFocus(NewTransactionModel.FocusInfo focusInfo) {
218 if (ignoreFocusChanges) {
219 Logger.debug("new-trans", "Ignoring focus change");
222 ignoreFocusChanges = true;
224 if (((focusInfo == null) || (focusInfo.element == null) ||
225 focusInfo.position != getBindingAdapterPosition()))
228 final NewTransactionModel.Item item = getItem();
232 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
233 switch (focusInfo.element) {
235 b.accountRowAccAmounts.requestFocus();
238 b.comment.setVisibility(View.VISIBLE);
239 b.comment.requestFocus();
242 boolean focused = b.accountRowAccName.requestFocus();
243 // b.accountRowAccName.dismissDropDown();
245 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
251 ignoreFocusChanges = false;
254 public void checkAmountValid(String s) {
255 boolean valid = true;
257 if (s.length() > 0) {
258 float ignored = Float.parseFloat(s.replace(decimalSeparator, decimalDot));
261 catch (NumberFormatException ex) {
265 displayAmountValidity(valid);
267 private void displayAmountValidity(boolean valid) {
268 b.accountRowAccAmounts.setCompoundDrawablesRelativeWithIntrinsicBounds(
269 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
270 b.accountRowAccAmounts.setMinEms(valid ? 4 : 5);
272 private void monitorComment(EditText editText) {
273 editText.addTextChangedListener(new TextWatcher() {
275 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
278 public void onTextChanged(CharSequence s, int start, int before, int count) {
281 public void afterTextChanged(Editable s) {
282 // debug("input", "text changed");
286 Logger.debug("textWatcher", "calling syncData()");
288 Logger.debug("textWatcher",
289 "syncData() returned, checking if transaction is submittable");
290 styleComment(editText, s.toString());
291 Logger.debug("textWatcher", "done");
295 private void commentFocusChanged(TextView textView, boolean hasFocus) {
296 @ColorInt int textColor;
297 textColor = b.dummyText.getTextColors()
300 textView.setTypeface(null, Typeface.NORMAL);
301 textView.setHint(R.string.transaction_account_comment_hint);
304 int alpha = (textColor >> 24 & 0xff);
305 alpha = 3 * alpha / 4;
306 textColor = (alpha << 24) | (0x00ffffff & textColor);
307 textView.setTypeface(null, Typeface.ITALIC);
308 textView.setHint("");
309 if (TextUtils.isEmpty(textView.getText())) {
310 textView.setVisibility(View.INVISIBLE);
313 textView.setTextColor(textColor);
316 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
317 ConstraintLayout.LayoutParams amountLP =
318 (ConstraintLayout.LayoutParams) b.accountRowAccAmounts.getLayoutParams();
319 ConstraintLayout.LayoutParams currencyLP =
320 (ConstraintLayout.LayoutParams) b.currency.getLayoutParams();
322 if (position == Currency.Position.before) {
323 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
324 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
326 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
327 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
328 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
329 amountLP.startToEnd = b.currency.getId();
331 b.currency.setGravity(Gravity.END);
334 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
335 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
337 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
338 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
339 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
340 amountLP.endToStart = b.currency.getId();
342 b.currency.setGravity(Gravity.START);
345 amountLP.resolveLayoutDirection(b.accountRowAccAmounts.getLayoutDirection());
346 currencyLP.resolveLayoutDirection(b.currency.getLayoutDirection());
348 b.accountRowAccAmounts.setLayoutParams(amountLP);
349 b.currency.setLayoutParams(currencyLP);
351 // distance between the amount and the currency symbol
352 int gapSize = DimensionUtils.sp2px(b.currency.getContext(), 5);
354 if (position == Currency.Position.before) {
355 b.currency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
358 b.currency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
361 private void setCurrencyString(String currency) {
362 @ColorInt int textColor = b.dummyText.getTextColors()
364 if (TextUtils.isEmpty(currency)) {
365 b.currency.setText(R.string.currency_symbol);
366 int alpha = (textColor >> 24) & 0xff;
367 alpha = alpha * 3 / 4;
368 b.currency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
371 b.currency.setText(currency);
372 b.currency.setTextColor(textColor);
375 private void setCurrency(Currency currency) {
376 setCurrencyString((currency == null) ? null : currency.getName());
378 private void setEditable(Boolean editable) {
379 b.accountRowAccName.setEnabled(editable);
380 b.accountRowAccAmounts.setEnabled(editable);
382 private void beginUpdates() {
384 throw new RuntimeException("Already in update mode");
387 private void endUpdates() {
389 throw new RuntimeException("Not in update mode");
395 * Stores the data from the UI elements into the model item
396 * Returns true if there were changes made that suggest transaction has to be
397 * checked for being submittable
399 private boolean syncData() {
401 Logger.debug("new-trans", "skipping syncData() loop");
405 if (getBindingAdapterPosition() == RecyclerView.NO_POSITION) {
406 // probably the row was swiped out
407 Logger.debug("new-trans", "Ignoring request to syncData(): adapter position negative");
411 final NewTransactionModel.Item item = getItem();
417 boolean significantChange = false;
420 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
422 // having account name is important
423 final Editable incomingAccountName = b.accountRowAccName.getText();
424 if (TextUtils.isEmpty(acc.getAccountName()) != TextUtils.isEmpty(incomingAccountName))
425 significantChange = true;
427 acc.setAccountName(String.valueOf(incomingAccountName));
428 final int accNameSelEnd = b.accountRowAccName.getSelectionEnd();
429 final int accNameSelStart = b.accountRowAccName.getSelectionStart();
430 acc.setAccountNameCursorPosition(accNameSelEnd);
432 acc.setComment(String.valueOf(b.comment.getText()));
434 String amount = String.valueOf(b.accountRowAccAmounts.getText());
435 amount = amount.trim();
437 if (amount.isEmpty()) {
438 if (acc.isAmountSet())
439 significantChange = true;
441 acc.setAmountValid(true);
445 amount = amount.replace(decimalSeparator, decimalDot);
446 final float parsedAmount = Float.parseFloat(amount);
447 if (!acc.isAmountSet() || !Misc.equalFloats(parsedAmount, acc.getAmount()))
448 significantChange = true;
449 acc.setAmount(parsedAmount);
450 acc.setAmountValid(true);
452 catch (NumberFormatException e) {
453 Logger.debug("new-trans", String.format(
454 "assuming amount is not set due to number format exception. " +
455 "input was '%s'", amount));
456 if (acc.isAmountValid())
457 significantChange = true;
459 acc.setAmountValid(false);
461 final String curr = String.valueOf(b.currency.getText());
462 final String currValue;
463 if (curr.equals(b.currency.getContext()
465 .getString(R.string.currency_symbol)) || curr.isEmpty())
470 if (!significantChange && !Misc.equalStrings(acc.getCurrency(), currValue))
471 significantChange = true;
472 acc.setCurrency(currValue);
475 return significantChange;
484 * @param item updates the UI elements with the data from the model item
486 @SuppressLint("DefaultLocale")
487 public void bind(@NonNull NewTransactionModel.Item item) {
492 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
494 final String incomingAccountName = acc.getAccountName();
495 final String presentAccountName = String.valueOf(b.accountRowAccName.getText());
496 if (!Misc.equalStrings(incomingAccountName, presentAccountName)) {
498 String.format("Setting account name from '%s' to '%s' (| @ %d)",
499 presentAccountName, incomingAccountName,
500 acc.getAccountNameCursorPosition()));
501 // avoid triggering completion pop-up
502 AccountWithAmountsAutocompleteAdapter a =
503 (AccountWithAmountsAutocompleteAdapter) b.accountRowAccName.getAdapter();
505 b.accountRowAccName.setAdapter(null);
506 b.accountRowAccName.setText(incomingAccountName);
507 b.accountRowAccName.setSelection(acc.getAccountNameCursorPosition());
510 b.accountRowAccName.setAdapter(a);
514 final String amountHint = acc.getAmountHint();
515 if (amountHint == null) {
516 b.accountRowAccAmounts.setHint(R.string.zero_amount);
519 b.accountRowAccAmounts.setHint(amountHint);
522 b.accountRowAccAmounts.setImeOptions(
523 acc.isLast() ? EditorInfo.IME_ACTION_DONE : EditorInfo.IME_ACTION_NEXT);
525 setCurrencyString(acc.getCurrency());
526 b.accountRowAccAmounts.setText(
527 acc.isAmountSet() ? String.format("%4.2f", acc.getAmount()) : null);
528 displayAmountValidity(true);
530 final String comment = acc.getComment();
531 b.comment.setText(comment);
532 styleComment(b.comment, comment);
536 NewTransactionItemsAdapter adapter =
537 (NewTransactionItemsAdapter) getBindingAdapter();
539 applyFocus(adapter.model.getFocusInfo()
550 private void styleComment(EditText editText, String comment) {
551 final View focusedView = editText.findFocus();
552 editText.setTypeface(null, (focusedView == editText) ? Typeface.NORMAL : Typeface.ITALIC);
553 editText.setVisibility(
554 ((focusedView != editText) && TextUtils.isEmpty(comment)) ? View.INVISIBLE