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;
35 import net.ktnx.mobileledger.R;
36 import net.ktnx.mobileledger.databinding.NewTransactionAccountRowBinding;
37 import net.ktnx.mobileledger.db.AccountAutocompleteAdapter;
38 import net.ktnx.mobileledger.model.Currency;
39 import net.ktnx.mobileledger.model.Data;
40 import net.ktnx.mobileledger.ui.CurrencySelectorFragment;
41 import net.ktnx.mobileledger.ui.TextViewClearHelper;
42 import net.ktnx.mobileledger.utils.DimensionUtils;
43 import net.ktnx.mobileledger.utils.Logger;
44 import net.ktnx.mobileledger.utils.Misc;
46 import java.text.DecimalFormatSymbols;
48 class NewTransactionAccountRowItemHolder extends NewTransactionItemViewHolder {
49 private final String decimalDot = ".";
50 private final NewTransactionAccountRowBinding b;
51 private boolean ignoreFocusChanges = false;
52 private String decimalSeparator;
53 private boolean inUpdate = false;
54 private boolean syncingData = false;
55 //TODO multiple amounts with different currencies per posting?
56 NewTransactionAccountRowItemHolder(@NonNull NewTransactionAccountRowBinding b,
57 NewTransactionItemsAdapter adapter) {
58 super(b.getRoot(), 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 = getAdapterPosition();
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(c -> adapter.setItemCurrency(getAdapterPosition(),
181 (c == null) ? null : c.getName()));
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 != getAdapterPosition()))
227 NewTransactionModel.TransactionAccount acc = getItem().toTransactionAccount();
228 switch (focusInfo.element) {
230 b.accountRowAccAmounts.requestFocus();
233 b.comment.setVisibility(View.VISIBLE);
234 b.comment.requestFocus();
237 boolean focused = b.accountRowAccName.requestFocus();
238 // b.accountRowAccName.dismissDropDown();
240 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
246 ignoreFocusChanges = false;
249 public void checkAmountValid(String s) {
250 boolean valid = true;
252 if (s.length() > 0) {
253 float ignored = Float.parseFloat(s.replace(decimalSeparator, decimalDot));
256 catch (NumberFormatException ex) {
260 displayAmountValidity(valid);
262 private void displayAmountValidity(boolean valid) {
263 b.accountRowAccAmounts.setCompoundDrawablesRelativeWithIntrinsicBounds(
264 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
265 b.accountRowAccAmounts.setMinEms(valid ? 4 : 5);
267 private void monitorComment(EditText editText) {
268 editText.addTextChangedListener(new TextWatcher() {
270 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
273 public void onTextChanged(CharSequence s, int start, int before, int count) {
276 public void afterTextChanged(Editable s) {
277 // debug("input", "text changed");
281 Logger.debug("textWatcher", "calling syncData()");
283 Logger.debug("textWatcher",
284 "syncData() returned, checking if transaction is submittable");
285 styleComment(editText, s.toString());
286 Logger.debug("textWatcher", "done");
290 private void commentFocusChanged(TextView textView, boolean hasFocus) {
291 @ColorInt int textColor;
292 textColor = b.dummyText.getTextColors()
295 textView.setTypeface(null, Typeface.NORMAL);
296 textView.setHint(R.string.transaction_account_comment_hint);
299 int alpha = (textColor >> 24 & 0xff);
300 alpha = 3 * alpha / 4;
301 textColor = (alpha << 24) | (0x00ffffff & textColor);
302 textView.setTypeface(null, Typeface.ITALIC);
303 textView.setHint("");
304 if (TextUtils.isEmpty(textView.getText())) {
305 textView.setVisibility(View.INVISIBLE);
308 textView.setTextColor(textColor);
311 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
312 ConstraintLayout.LayoutParams amountLP =
313 (ConstraintLayout.LayoutParams) b.accountRowAccAmounts.getLayoutParams();
314 ConstraintLayout.LayoutParams currencyLP =
315 (ConstraintLayout.LayoutParams) b.currency.getLayoutParams();
317 if (position == Currency.Position.before) {
318 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
319 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
321 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
322 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
323 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
324 amountLP.startToEnd = b.currency.getId();
326 b.currency.setGravity(Gravity.END);
329 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
330 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
332 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
333 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
334 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
335 amountLP.endToStart = b.currency.getId();
337 b.currency.setGravity(Gravity.START);
340 amountLP.resolveLayoutDirection(b.accountRowAccAmounts.getLayoutDirection());
341 currencyLP.resolveLayoutDirection(b.currency.getLayoutDirection());
343 b.accountRowAccAmounts.setLayoutParams(amountLP);
344 b.currency.setLayoutParams(currencyLP);
346 // distance between the amount and the currency symbol
347 int gapSize = DimensionUtils.sp2px(b.currency.getContext(), 5);
349 if (position == Currency.Position.before) {
350 b.currency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
353 b.currency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
356 private void setCurrencyString(String currency) {
357 @ColorInt int textColor = b.dummyText.getTextColors()
359 if (TextUtils.isEmpty(currency)) {
360 b.currency.setText(R.string.currency_symbol);
361 int alpha = (textColor >> 24) & 0xff;
362 alpha = alpha * 3 / 4;
363 b.currency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
366 b.currency.setText(currency);
367 b.currency.setTextColor(textColor);
370 private void setCurrency(Currency currency) {
371 setCurrencyString((currency == null) ? null : currency.getName());
373 private void setEditable(Boolean editable) {
374 b.accountRowAccName.setEnabled(editable);
375 b.accountRowAccAmounts.setEnabled(editable);
377 private void beginUpdates() {
379 throw new RuntimeException("Already in update mode");
382 private void endUpdates() {
384 throw new RuntimeException("Not in update mode");
390 * Stores the data from the UI elements into the model item
391 * Returns true if there were changes made that suggest transaction has to be
392 * checked for being submittable
394 private boolean syncData() {
396 Logger.debug("new-trans", "skipping syncData() loop");
400 if (getAdapterPosition() < 0) {
401 // probably the row was swiped out
402 Logger.debug("new-trans", "Ignoring request to suncData(): adapter position negative");
406 NewTransactionModel.Item item = getItem();
410 boolean significantChange = false;
413 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
415 // having account name is important
416 final Editable incomingAccountName = b.accountRowAccName.getText();
417 if (TextUtils.isEmpty(acc.getAccountName()) != TextUtils.isEmpty(incomingAccountName))
418 significantChange = true;
420 acc.setAccountName(String.valueOf(incomingAccountName));
421 final int accNameSelEnd = b.accountRowAccName.getSelectionEnd();
422 final int accNameSelStart = b.accountRowAccName.getSelectionStart();
423 acc.setAccountNameCursorPosition(accNameSelEnd);
425 acc.setComment(String.valueOf(b.comment.getText()));
427 String amount = String.valueOf(b.accountRowAccAmounts.getText());
428 amount = amount.trim();
430 if (amount.isEmpty()) {
431 if (acc.isAmountSet())
432 significantChange = true;
434 acc.setAmountValid(true);
438 amount = amount.replace(decimalSeparator, decimalDot);
439 final float parsedAmount = Float.parseFloat(amount);
440 if (!acc.isAmountSet() || !Misc.equalFloats(parsedAmount, acc.getAmount()))
441 significantChange = true;
442 acc.setAmount(parsedAmount);
443 acc.setAmountValid(true);
445 catch (NumberFormatException e) {
446 Logger.debug("new-trans", String.format(
447 "assuming amount is not set due to number format exception. " +
448 "input was '%s'", amount));
449 if (acc.isAmountValid())
450 significantChange = true;
451 acc.setAmountValid(false);
453 final String curr = String.valueOf(b.currency.getText());
454 final String currValue;
455 if (curr.equals(b.currency.getContext()
457 .getString(R.string.currency_symbol)) || curr.isEmpty())
462 if (!significantChange && !Misc.equalStrings(acc.getCurrency(), currValue))
463 significantChange = true;
464 acc.setCurrency(currValue);
467 return significantChange;
476 * @param item updates the UI elements with the data from the model item
478 @SuppressLint("DefaultLocale")
479 public void bind(@NonNull NewTransactionModel.Item item) {
484 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
486 final String incomingAccountName = acc.getAccountName();
487 final String presentAccountName = String.valueOf(b.accountRowAccName.getText());
488 if (!Misc.equalStrings(incomingAccountName, presentAccountName)) {
490 String.format("Setting account name from '%s' to '%s' (| @ %d)",
491 presentAccountName, incomingAccountName,
492 acc.getAccountNameCursorPosition()));
493 // avoid triggering completion pop-up
494 AccountAutocompleteAdapter a =
495 (AccountAutocompleteAdapter) b.accountRowAccName.getAdapter();
497 b.accountRowAccName.setAdapter(null);
498 b.accountRowAccName.setText(incomingAccountName);
499 b.accountRowAccName.setSelection(acc.getAccountNameCursorPosition());
502 b.accountRowAccName.setAdapter(a);
506 final String amountHint = acc.getAmountHint();
507 if (amountHint == null) {
508 b.accountRowAccAmounts.setHint(R.string.zero_amount);
511 b.accountRowAccAmounts.setHint(amountHint);
514 b.accountRowAccAmounts.setImeOptions(
515 acc.isLast() ? EditorInfo.IME_ACTION_DONE : EditorInfo.IME_ACTION_NEXT);
517 setCurrencyString(acc.getCurrency());
518 b.accountRowAccAmounts.setText(
519 acc.isAmountSet() ? String.format("%4.2f", acc.getAmount()) : null);
520 displayAmountValidity(true);
522 b.comment.setText(acc.getComment());
526 applyFocus(mAdapter.model.getFocusInfo()
537 private void styleComment(EditText editText, String comment) {
538 final View focusedView = editText.findFocus();
539 editText.setTypeface(null, (focusedView == editText) ? Typeface.NORMAL : Typeface.ITALIC);
540 editText.setVisibility(
541 ((focusedView != editText) && TextUtils.isEmpty(comment)) ? View.INVISIBLE