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()
130 b.accountRowAccName.setOnItemClickListener((parent, view, position, id) -> {
131 adapter.noteFocusIsOnAmount(position);
134 final TextWatcher tw = new TextWatcher() {
136 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
140 public void onTextChanged(CharSequence s, int start, int before, int count) {
144 public void afterTextChanged(Editable s) {
145 // debug("input", "text changed");
149 Logger.debug("textWatcher", "calling syncData()");
151 Logger.debug("textWatcher",
152 "syncData() returned, checking if transaction is submittable");
153 adapter.model.checkTransactionSubmittable(null);
155 Logger.debug("textWatcher", "done");
158 final TextWatcher amountWatcher = new TextWatcher() {
160 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
162 public void onTextChanged(CharSequence s, int start, int before, int count) {}
164 public void afterTextChanged(Editable s) {
165 checkAmountValid(s.toString());
168 adapter.model.checkTransactionSubmittable(null);
171 b.accountRowAccName.addTextChangedListener(tw);
172 monitorComment(b.comment);
173 b.accountRowAccAmounts.addTextChangedListener(amountWatcher);
175 b.currencyButton.setOnClickListener(v -> {
176 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
177 cpf.showPositionAndPadding();
178 cpf.setOnCurrencySelectedListener(
179 c -> adapter.setItemCurrency(getBindingAdapterPosition(), c));
180 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
183 commentFocusChanged(b.comment, false);
185 adapter.model.getFocusInfo()
186 .observe(activity, this::applyFocus);
188 Data.currencyGap.observe(activity,
189 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
192 Data.currencySymbolPosition.observe(activity,
193 position -> updateCurrencyPositionAndPadding(position,
194 Data.currencyGap.getValue()));
196 adapter.model.getShowCurrency()
197 .observe(activity, showCurrency -> {
199 b.currency.setVisibility(View.VISIBLE);
200 b.currencyButton.setVisibility(View.VISIBLE);
201 setCurrencyString(mProfile.getDefaultCommodity());
204 b.currency.setVisibility(View.GONE);
205 b.currencyButton.setVisibility(View.GONE);
206 setCurrencyString(null);
210 adapter.model.getShowComments()
211 .observe(activity, show -> b.commentLayout.setVisibility(
212 show ? View.VISIBLE : View.GONE));
214 private void applyFocus(NewTransactionModel.FocusInfo focusInfo) {
215 if (ignoreFocusChanges) {
216 Logger.debug("new-trans", "Ignoring focus change");
219 ignoreFocusChanges = true;
221 if (((focusInfo == null) || (focusInfo.element == null) ||
222 focusInfo.position != getBindingAdapterPosition()))
225 final NewTransactionModel.Item item = getItem();
229 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
230 switch (focusInfo.element) {
232 b.accountRowAccAmounts.requestFocus();
235 b.comment.setVisibility(View.VISIBLE);
236 b.comment.requestFocus();
239 boolean focused = b.accountRowAccName.requestFocus();
240 // b.accountRowAccName.dismissDropDown();
242 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
248 ignoreFocusChanges = false;
251 public void checkAmountValid(String s) {
252 // FIXME this needs to be done in the model only
253 boolean valid = true;
255 if (s.length() > 0) {
257 Float.parseFloat(s.replace(Data.getDecimalSeparator(), Data.decimalDot));
260 catch (NumberFormatException ex) {
262 float ignored = Data.parseNumber(s);
264 catch (ParseException ex2) {
269 displayAmountValidity(valid);
271 private void displayAmountValidity(boolean valid) {
272 b.accountRowAccAmounts.setCompoundDrawablesRelativeWithIntrinsicBounds(
273 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
274 b.accountRowAccAmounts.setMinEms(valid ? 4 : 5);
276 private void monitorComment(EditText editText) {
277 editText.addTextChangedListener(new TextWatcher() {
279 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
282 public void onTextChanged(CharSequence s, int start, int before, int count) {
285 public void afterTextChanged(Editable s) {
286 // debug("input", "text changed");
290 Logger.debug("textWatcher", "calling syncData()");
292 Logger.debug("textWatcher",
293 "syncData() returned, checking if transaction is submittable");
294 styleComment(editText, s.toString());
295 Logger.debug("textWatcher", "done");
299 private void commentFocusChanged(TextView textView, boolean hasFocus) {
300 @ColorInt int textColor;
301 textColor = b.dummyText.getTextColors()
304 textView.setTypeface(null, Typeface.NORMAL);
305 textView.setHint(R.string.transaction_account_comment_hint);
308 int alpha = (textColor >> 24 & 0xff);
309 alpha = 3 * alpha / 4;
310 textColor = (alpha << 24) | (0x00ffffff & textColor);
311 textView.setTypeface(null, Typeface.ITALIC);
312 textView.setHint("");
313 if (TextUtils.isEmpty(textView.getText())) {
314 textView.setVisibility(View.INVISIBLE);
317 textView.setTextColor(textColor);
320 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
321 ConstraintLayout.LayoutParams amountLP =
322 (ConstraintLayout.LayoutParams) b.accountRowAccAmounts.getLayoutParams();
323 ConstraintLayout.LayoutParams currencyLP =
324 (ConstraintLayout.LayoutParams) b.currency.getLayoutParams();
326 if (position == Currency.Position.before) {
327 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
328 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
330 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
331 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
332 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
333 amountLP.startToEnd = b.currency.getId();
335 b.currency.setGravity(Gravity.END);
338 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
339 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
341 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
342 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
343 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
344 amountLP.endToStart = b.currency.getId();
346 b.currency.setGravity(Gravity.START);
349 amountLP.resolveLayoutDirection(b.accountRowAccAmounts.getLayoutDirection());
350 currencyLP.resolveLayoutDirection(b.currency.getLayoutDirection());
352 b.accountRowAccAmounts.setLayoutParams(amountLP);
353 b.currency.setLayoutParams(currencyLP);
355 // distance between the amount and the currency symbol
356 int gapSize = DimensionUtils.sp2px(b.currency.getContext(), 5);
358 if (position == Currency.Position.before) {
359 b.currency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
362 b.currency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
365 private void setCurrencyString(String currency) {
366 @ColorInt int textColor = b.dummyText.getTextColors()
368 if (TextUtils.isEmpty(currency)) {
369 b.currency.setText(R.string.currency_symbol);
370 int alpha = (textColor >> 24) & 0xff;
371 alpha = alpha * 3 / 4;
372 b.currency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
375 b.currency.setText(currency);
376 b.currency.setTextColor(textColor);
379 private void setCurrency(Currency currency) {
380 setCurrencyString((currency == null) ? null : currency.getName());
382 private void setEditable(Boolean editable) {
383 b.accountRowAccName.setEnabled(editable);
384 b.accountRowAccAmounts.setEnabled(editable);
386 private void beginUpdates() {
388 throw new RuntimeException("Already in update mode");
391 private void endUpdates() {
393 throw new RuntimeException("Not in update mode");
399 * Stores the data from the UI elements into the model item
400 * Returns true if there were changes made that suggest transaction has to be
401 * checked for being submittable
403 private boolean syncData() {
405 Logger.debug("new-trans", "skipping syncData() loop");
409 if (getBindingAdapterPosition() == RecyclerView.NO_POSITION) {
410 // probably the row was swiped out
411 Logger.debug("new-trans", "Ignoring request to syncData(): adapter position negative");
415 final NewTransactionModel.Item item = getItem();
421 boolean significantChange = false;
424 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
426 // having account name is important
427 final Editable incomingAccountName = b.accountRowAccName.getText();
428 if (TextUtils.isEmpty(acc.getAccountName()) != TextUtils.isEmpty(incomingAccountName))
429 significantChange = true;
431 acc.setAccountName(String.valueOf(incomingAccountName));
432 final int accNameSelEnd = b.accountRowAccName.getSelectionEnd();
433 final int accNameSelStart = b.accountRowAccName.getSelectionStart();
434 acc.setAccountNameCursorPosition(accNameSelEnd);
436 acc.setComment(String.valueOf(b.comment.getText()));
438 String amount = String.valueOf(b.accountRowAccAmounts.getText());
440 if (acc.setAndCheckAmountText(Misc.nullIsEmpty(amount)))
441 significantChange = true;
442 displayAmountValidity(!acc.isAmountSet() || acc.isAmountValid());
444 final String curr = String.valueOf(b.currency.getText());
445 final String currValue;
446 if (curr.equals(b.currency.getContext()
448 .getString(R.string.currency_symbol)) || curr.isEmpty())
453 if (!significantChange && !Misc.equalStrings(acc.getCurrency(), currValue))
454 significantChange = true;
455 acc.setCurrency(currValue);
457 return significantChange;
466 * @param item updates the UI elements with the data from the model item
468 @SuppressLint("DefaultLocale")
469 public void bind(@NonNull NewTransactionModel.Item item) {
474 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
476 final String incomingAccountName = acc.getAccountName();
477 final String presentAccountName = String.valueOf(b.accountRowAccName.getText());
478 if (!Misc.equalStrings(incomingAccountName, presentAccountName)) {
480 String.format("Setting account name from '%s' to '%s' (| @ %d)",
481 presentAccountName, incomingAccountName,
482 acc.getAccountNameCursorPosition()));
483 // avoid triggering completion pop-up
484 AccountWithAmountsAutocompleteAdapter a =
485 (AccountWithAmountsAutocompleteAdapter) b.accountRowAccName.getAdapter();
487 b.accountRowAccName.setAdapter(null);
488 b.accountRowAccName.setText(incomingAccountName);
489 b.accountRowAccName.setSelection(acc.getAccountNameCursorPosition());
492 b.accountRowAccName.setAdapter(a);
496 final String amountHint = acc.getAmountHint();
497 if (amountHint == null) {
498 b.accountRowAccAmounts.setHint(R.string.zero_amount);
501 b.accountRowAccAmounts.setHint(amountHint);
504 b.accountRowAccAmounts.setImeOptions(
505 acc.isLast() ? EditorInfo.IME_ACTION_DONE : EditorInfo.IME_ACTION_NEXT);
507 setCurrencyString(acc.getCurrency());
508 b.accountRowAccAmounts.setText(acc.getAmountText());
509 displayAmountValidity(!acc.isAmountSet() || acc.isAmountValid());
511 final String comment = acc.getComment();
512 b.comment.setText(comment);
513 styleComment(b.comment, comment);
517 NewTransactionItemsAdapter adapter =
518 (NewTransactionItemsAdapter) getBindingAdapter();
520 applyFocus(adapter.model.getFocusInfo()
531 private void styleComment(EditText editText, String comment) {
532 final View focusedView = editText.findFocus();
533 editText.setTypeface(null, (focusedView == editText) ? Typeface.NORMAL : Typeface.ITALIC);
534 editText.setVisibility(
535 ((focusedView != editText) && TextUtils.isEmpty(comment)) ? View.INVISIBLE