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.ParseException;
49 class NewTransactionAccountRowItemHolder extends NewTransactionItemViewHolder {
50 private final NewTransactionAccountRowBinding b;
51 private boolean ignoreFocusChanges = false;
52 private boolean inUpdate = false;
53 private boolean syncingData = false;
54 NewTransactionAccountRowItemHolder(@NonNull NewTransactionAccountRowBinding b,
55 NewTransactionItemsAdapter adapter) {
58 new TextViewClearHelper().attachToTextView(b.comment);
60 b.accountRowAccName.setNextFocusForwardId(View.NO_ID);
61 b.accountRowAccAmounts.setNextFocusForwardId(View.NO_ID); // magic!
63 b.accountCommentButton.setOnClickListener(v -> {
64 b.comment.setVisibility(View.VISIBLE);
65 b.comment.requestFocus();
68 @SuppressLint("DefaultLocale") View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
69 final int id = v.getId();
71 boolean wasSyncing = syncingData;
74 final int pos = getBindingAdapterPosition();
75 if (id == R.id.account_row_acc_name) {
76 adapter.noteFocusIsOnAccount(pos);
78 else if (id == R.id.account_row_acc_amounts) {
79 adapter.noteFocusIsOnAmount(pos);
81 else if (id == R.id.comment) {
82 adapter.noteFocusIsOnComment(pos);
85 throw new IllegalStateException("Where is the focus? " + id);
88 syncingData = wasSyncing;
92 if (id == R.id.account_row_acc_amounts) {
94 String input = String.valueOf(b.accountRowAccAmounts.getText());
95 input = input.replace(Data.getDecimalSeparator(), Data.decimalDot);
96 final String newText = Data.formatNumber(Float.parseFloat(input));
97 if (!newText.equals(input)) {
98 boolean wasSyncingData = syncingData;
101 // there is a listener that will propagate the change to the model
102 b.accountRowAccAmounts.setText(newText);
105 syncingData = wasSyncingData;
109 catch (NumberFormatException ex) {
115 if (id == R.id.comment) {
116 commentFocusChanged(b.comment, hasFocus);
120 b.accountRowAccName.setOnFocusChangeListener(focusMonitor);
121 b.accountRowAccAmounts.setOnFocusChangeListener(focusMonitor);
122 b.comment.setOnFocusChangeListener(focusMonitor);
124 NewTransactionActivity activity = (NewTransactionActivity) b.getRoot()
127 b.accountRowAccName.setAdapter(new AccountWithAmountsAutocompleteAdapter(b.getRoot()
131 final TextWatcher tw = new TextWatcher() {
133 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
137 public void onTextChanged(CharSequence s, int start, int before, int count) {
141 public void afterTextChanged(Editable s) {
142 // debug("input", "text changed");
146 Logger.debug("textWatcher", "calling syncData()");
148 Logger.debug("textWatcher",
149 "syncData() returned, checking if transaction is submittable");
150 adapter.model.checkTransactionSubmittable(null);
152 Logger.debug("textWatcher", "done");
155 final TextWatcher amountWatcher = new TextWatcher() {
157 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
159 public void onTextChanged(CharSequence s, int start, int before, int count) {}
161 public void afterTextChanged(Editable s) {
162 checkAmountValid(s.toString());
165 adapter.model.checkTransactionSubmittable(null);
168 b.accountRowAccName.addTextChangedListener(tw);
169 monitorComment(b.comment);
170 b.accountRowAccAmounts.addTextChangedListener(amountWatcher);
172 b.currencyButton.setOnClickListener(v -> {
173 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
174 cpf.showPositionAndPadding();
175 cpf.setOnCurrencySelectedListener(
176 c -> adapter.setItemCurrency(getBindingAdapterPosition(), c));
177 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
180 commentFocusChanged(b.comment, false);
182 adapter.model.getFocusInfo()
183 .observe(activity, this::applyFocus);
185 Data.currencyGap.observe(activity,
186 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
189 Data.currencySymbolPosition.observe(activity,
190 position -> updateCurrencyPositionAndPadding(position,
191 Data.currencyGap.getValue()));
193 adapter.model.getShowCurrency()
194 .observe(activity, showCurrency -> {
196 b.currency.setVisibility(View.VISIBLE);
197 b.currencyButton.setVisibility(View.VISIBLE);
198 setCurrencyString(mProfile.getDefaultCommodity());
201 b.currency.setVisibility(View.GONE);
202 b.currencyButton.setVisibility(View.GONE);
203 setCurrencyString(null);
207 adapter.model.getShowComments()
208 .observe(activity, show -> b.commentLayout.setVisibility(
209 show ? View.VISIBLE : View.GONE));
211 private void applyFocus(NewTransactionModel.FocusInfo focusInfo) {
212 if (ignoreFocusChanges) {
213 Logger.debug("new-trans", "Ignoring focus change");
216 ignoreFocusChanges = true;
218 if (((focusInfo == null) || (focusInfo.element == null) ||
219 focusInfo.position != getBindingAdapterPosition()))
222 final NewTransactionModel.Item item = getItem();
226 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
227 switch (focusInfo.element) {
229 b.accountRowAccAmounts.requestFocus();
232 b.comment.setVisibility(View.VISIBLE);
233 b.comment.requestFocus();
236 boolean focused = b.accountRowAccName.requestFocus();
237 // b.accountRowAccName.dismissDropDown();
239 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
245 ignoreFocusChanges = false;
248 public void checkAmountValid(String s) {
249 // FIXME this needs to be done in the model only
250 boolean valid = true;
252 if (s.length() > 0) {
254 Float.parseFloat(s.replace(Data.getDecimalSeparator(), Data.decimalDot));
257 catch (NumberFormatException ex) {
259 float ignored = Data.parseNumber(s);
261 catch (ParseException ex2) {
266 displayAmountValidity(valid);
268 private void displayAmountValidity(boolean valid) {
269 b.accountRowAccAmounts.setCompoundDrawablesRelativeWithIntrinsicBounds(
270 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
271 b.accountRowAccAmounts.setMinEms(valid ? 4 : 5);
273 private void monitorComment(EditText editText) {
274 editText.addTextChangedListener(new TextWatcher() {
276 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
279 public void onTextChanged(CharSequence s, int start, int before, int count) {
282 public void afterTextChanged(Editable s) {
283 // debug("input", "text changed");
287 Logger.debug("textWatcher", "calling syncData()");
289 Logger.debug("textWatcher",
290 "syncData() returned, checking if transaction is submittable");
291 styleComment(editText, s.toString());
292 Logger.debug("textWatcher", "done");
296 private void commentFocusChanged(TextView textView, boolean hasFocus) {
297 @ColorInt int textColor;
298 textColor = b.dummyText.getTextColors()
301 textView.setTypeface(null, Typeface.NORMAL);
302 textView.setHint(R.string.transaction_account_comment_hint);
305 int alpha = (textColor >> 24 & 0xff);
306 alpha = 3 * alpha / 4;
307 textColor = (alpha << 24) | (0x00ffffff & textColor);
308 textView.setTypeface(null, Typeface.ITALIC);
309 textView.setHint("");
310 if (TextUtils.isEmpty(textView.getText())) {
311 textView.setVisibility(View.INVISIBLE);
314 textView.setTextColor(textColor);
317 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
318 ConstraintLayout.LayoutParams amountLP =
319 (ConstraintLayout.LayoutParams) b.accountRowAccAmounts.getLayoutParams();
320 ConstraintLayout.LayoutParams currencyLP =
321 (ConstraintLayout.LayoutParams) b.currency.getLayoutParams();
323 if (position == Currency.Position.before) {
324 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
325 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
327 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
328 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
329 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
330 amountLP.startToEnd = b.currency.getId();
332 b.currency.setGravity(Gravity.END);
335 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
336 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
338 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
339 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
340 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
341 amountLP.endToStart = b.currency.getId();
343 b.currency.setGravity(Gravity.START);
346 amountLP.resolveLayoutDirection(b.accountRowAccAmounts.getLayoutDirection());
347 currencyLP.resolveLayoutDirection(b.currency.getLayoutDirection());
349 b.accountRowAccAmounts.setLayoutParams(amountLP);
350 b.currency.setLayoutParams(currencyLP);
352 // distance between the amount and the currency symbol
353 int gapSize = DimensionUtils.sp2px(b.currency.getContext(), 5);
355 if (position == Currency.Position.before) {
356 b.currency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
359 b.currency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
362 private void setCurrencyString(String currency) {
363 @ColorInt int textColor = b.dummyText.getTextColors()
365 if (TextUtils.isEmpty(currency)) {
366 b.currency.setText(R.string.currency_symbol);
367 int alpha = (textColor >> 24) & 0xff;
368 alpha = alpha * 3 / 4;
369 b.currency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
372 b.currency.setText(currency);
373 b.currency.setTextColor(textColor);
376 private void setCurrency(Currency currency) {
377 setCurrencyString((currency == null) ? null : currency.getName());
379 private void setEditable(Boolean editable) {
380 b.accountRowAccName.setEnabled(editable);
381 b.accountRowAccAmounts.setEnabled(editable);
383 private void beginUpdates() {
385 throw new RuntimeException("Already in update mode");
388 private void endUpdates() {
390 throw new RuntimeException("Not in update mode");
396 * Stores the data from the UI elements into the model item
397 * Returns true if there were changes made that suggest transaction has to be
398 * checked for being submittable
400 private boolean syncData() {
402 Logger.debug("new-trans", "skipping syncData() loop");
406 if (getBindingAdapterPosition() == RecyclerView.NO_POSITION) {
407 // probably the row was swiped out
408 Logger.debug("new-trans", "Ignoring request to syncData(): adapter position negative");
412 final NewTransactionModel.Item item = getItem();
418 boolean significantChange = false;
421 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
423 // having account name is important
424 final Editable incomingAccountName = b.accountRowAccName.getText();
425 if (TextUtils.isEmpty(acc.getAccountName()) != TextUtils.isEmpty(incomingAccountName))
426 significantChange = true;
428 acc.setAccountName(String.valueOf(incomingAccountName));
429 final int accNameSelEnd = b.accountRowAccName.getSelectionEnd();
430 final int accNameSelStart = b.accountRowAccName.getSelectionStart();
431 acc.setAccountNameCursorPosition(accNameSelEnd);
433 acc.setComment(String.valueOf(b.comment.getText()));
435 String amount = String.valueOf(b.accountRowAccAmounts.getText());
437 if (acc.setAndCheckAmountText(Misc.nullIsEmpty(amount)))
438 significantChange = true;
439 displayAmountValidity(!acc.isAmountSet() || acc.isAmountValid());
441 final String curr = String.valueOf(b.currency.getText());
442 final String currValue;
443 if (curr.equals(b.currency.getContext()
445 .getString(R.string.currency_symbol)) || curr.isEmpty())
450 if (!significantChange && !Misc.equalStrings(acc.getCurrency(), currValue))
451 significantChange = true;
452 acc.setCurrency(currValue);
454 return significantChange;
463 * @param item updates the UI elements with the data from the model item
465 @SuppressLint("DefaultLocale")
466 public void bind(@NonNull NewTransactionModel.Item item) {
471 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
473 final String incomingAccountName = acc.getAccountName();
474 final String presentAccountName = String.valueOf(b.accountRowAccName.getText());
475 if (!Misc.equalStrings(incomingAccountName, presentAccountName)) {
477 String.format("Setting account name from '%s' to '%s' (| @ %d)",
478 presentAccountName, incomingAccountName,
479 acc.getAccountNameCursorPosition()));
480 // avoid triggering completion pop-up
481 AccountWithAmountsAutocompleteAdapter a =
482 (AccountWithAmountsAutocompleteAdapter) b.accountRowAccName.getAdapter();
484 b.accountRowAccName.setAdapter(null);
485 b.accountRowAccName.setText(incomingAccountName);
486 b.accountRowAccName.setSelection(acc.getAccountNameCursorPosition());
489 b.accountRowAccName.setAdapter(a);
493 final String amountHint = acc.getAmountHint();
494 if (amountHint == null) {
495 b.accountRowAccAmounts.setHint(R.string.zero_amount);
498 b.accountRowAccAmounts.setHint(amountHint);
501 b.accountRowAccAmounts.setImeOptions(
502 acc.isLast() ? EditorInfo.IME_ACTION_DONE : EditorInfo.IME_ACTION_NEXT);
504 setCurrencyString(acc.getCurrency());
505 b.accountRowAccAmounts.setText(acc.getAmountText());
506 displayAmountValidity(!acc.isAmountSet() || acc.isAmountValid());
508 final String comment = acc.getComment();
509 b.comment.setText(comment);
510 styleComment(b.comment, comment);
514 NewTransactionItemsAdapter adapter =
515 (NewTransactionItemsAdapter) getBindingAdapter();
517 applyFocus(adapter.model.getFocusInfo()
528 private void styleComment(EditText editText, String comment) {
529 final View focusedView = editText.findFocus();
530 editText.setTypeface(null, (focusedView == editText) ? Typeface.NORMAL : Typeface.ITALIC);
531 editText.setVisibility(
532 ((focusedView != editText) && TextUtils.isEmpty(comment)) ? View.INVISIBLE