]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/new_transaction/NewTransactionItemHolder.java
3b69110a7c99cb8f75dc41e16e42c3a32f3e0da9
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / new_transaction / NewTransactionItemHolder.java
1 /*
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.ktnx.mobileledger.ui.new_transaction;
19
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.SimpleCursorAdapter;
30 import android.widget.TextView;
31
32 import androidx.annotation.ColorInt;
33 import androidx.annotation.NonNull;
34 import androidx.constraintlayout.widget.ConstraintLayout;
35 import androidx.recyclerview.widget.RecyclerView;
36
37 import net.ktnx.mobileledger.R;
38 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
39 import net.ktnx.mobileledger.databinding.NewTransactionRowBinding;
40 import net.ktnx.mobileledger.db.AccountAutocompleteAdapter;
41 import net.ktnx.mobileledger.model.Currency;
42 import net.ktnx.mobileledger.model.Data;
43 import net.ktnx.mobileledger.model.MobileLedgerProfile;
44 import net.ktnx.mobileledger.ui.CurrencySelectorFragment;
45 import net.ktnx.mobileledger.ui.DatePickerFragment;
46 import net.ktnx.mobileledger.ui.TextViewClearHelper;
47 import net.ktnx.mobileledger.utils.DimensionUtils;
48 import net.ktnx.mobileledger.utils.Logger;
49 import net.ktnx.mobileledger.utils.MLDB;
50 import net.ktnx.mobileledger.utils.Misc;
51 import net.ktnx.mobileledger.utils.SimpleDate;
52
53 import java.text.DecimalFormatSymbols;
54 import java.text.ParseException;
55 import java.util.Objects;
56
57 class NewTransactionItemHolder extends RecyclerView.ViewHolder
58         implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback {
59     private final String decimalDot = ".";
60     private final MobileLedgerProfile mProfile;
61     private final NewTransactionRowBinding b;
62     private final NewTransactionItemsAdapter mAdapter;
63     private boolean ignoreFocusChanges = false;
64     private String decimalSeparator;
65     private boolean inUpdate = false;
66     private boolean syncingData = false;
67     //TODO multiple amounts with different currencies per posting?
68     NewTransactionItemHolder(@NonNull NewTransactionRowBinding b,
69                              NewTransactionItemsAdapter adapter) {
70         super(b.getRoot());
71         this.b = b;
72         this.mAdapter = adapter;
73         new TextViewClearHelper().attachToTextView(b.comment);
74
75         b.newTransactionDescription.setNextFocusForwardId(View.NO_ID);
76         b.accountRowAccName.setNextFocusForwardId(View.NO_ID);
77         b.accountRowAccAmounts.setNextFocusForwardId(View.NO_ID); // magic!
78
79         b.newTransactionDate.setOnClickListener(v -> pickTransactionDate());
80
81         b.accountCommentButton.setOnClickListener(v -> {
82             b.comment.setVisibility(View.VISIBLE);
83             b.comment.requestFocus();
84         });
85
86         b.transactionCommentButton.setOnClickListener(v -> {
87             b.transactionComment.setVisibility(View.VISIBLE);
88             b.transactionComment.requestFocus();
89         });
90
91         mProfile = Data.getProfile();
92
93         @SuppressLint("DefaultLocale") View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
94             final int id = v.getId();
95             if (hasFocus) {
96                 boolean wasSyncing = syncingData;
97                 syncingData = true;
98                 try {
99                     final int pos = getAdapterPosition();
100                     if (id == R.id.account_row_acc_name) {
101                         adapter.noteFocusIsOnAccount(pos);
102                     }
103                     else if (id == R.id.account_row_acc_amounts) {
104                         adapter.noteFocusIsOnAmount(pos);
105                     }
106                     else if (id == R.id.comment) {
107                         adapter.noteFocusIsOnComment(pos);
108                     }
109                     else if (id == R.id.transaction_comment) {
110                         adapter.noteFocusIsOnTransactionComment(pos);
111                     }
112                     else if (id == R.id.new_transaction_description) {
113                         adapter.noteFocusIsOnDescription(pos);
114                     }
115                     else
116                         throw new IllegalStateException("Where is the focus?");
117                 }
118                 finally {
119                     syncingData = wasSyncing;
120                 }
121             }
122             else {  // lost focus
123                 if (id == R.id.account_row_acc_amounts) {
124                     try {
125                         String input = String.valueOf(b.accountRowAccAmounts.getText());
126                         input = input.replace(decimalSeparator, decimalDot);
127                         b.accountRowAccAmounts.setText(
128                                 String.format("%4.2f", Float.parseFloat(input)));
129                     }
130                     catch (NumberFormatException ex) {
131                         // ignored
132                     }
133                 }
134             }
135
136             if (id == R.id.comment) {
137                 commentFocusChanged(b.comment, hasFocus);
138             }
139             else if (id == R.id.transaction_comment) {
140                 commentFocusChanged(b.transactionComment, hasFocus);
141             }
142         };
143
144         b.newTransactionDescription.setOnFocusChangeListener(focusMonitor);
145         b.accountRowAccName.setOnFocusChangeListener(focusMonitor);
146         b.accountRowAccAmounts.setOnFocusChangeListener(focusMonitor);
147         b.comment.setOnFocusChangeListener(focusMonitor);
148         b.transactionComment.setOnFocusChangeListener(focusMonitor);
149
150         NewTransactionActivity activity = (NewTransactionActivity) b.getRoot()
151                                                                     .getContext();
152
153         MLDB.hookAutocompletionAdapter(activity, b.newTransactionDescription,
154                 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, activity, mProfile);
155         b.accountRowAccName.setAdapter(new AccountAutocompleteAdapter(b.getRoot()
156                                                                        .getContext(), mProfile));
157
158         decimalSeparator = "";
159         Data.locale.observe(activity, locale -> decimalSeparator = String.valueOf(
160                 DecimalFormatSymbols.getInstance(locale)
161                                     .getMonetaryDecimalSeparator()));
162
163         final TextWatcher tw = new TextWatcher() {
164             @Override
165             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
166             }
167
168             @Override
169             public void onTextChanged(CharSequence s, int start, int before, int count) {
170             }
171
172             @Override
173             public void afterTextChanged(Editable s) {
174 //                debug("input", "text changed");
175                 if (inUpdate)
176                     return;
177
178                 Logger.debug("textWatcher", "calling syncData()");
179                 if (syncData()) {
180                     Logger.debug("textWatcher",
181                             "syncData() returned, checking if transaction is submittable");
182                     adapter.model.checkTransactionSubmittable(null);
183                 }
184                 Logger.debug("textWatcher", "done");
185             }
186         };
187         final TextWatcher amountWatcher = new TextWatcher() {
188             @Override
189             public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
190             @Override
191             public void onTextChanged(CharSequence s, int start, int before, int count) {}
192             @Override
193             public void afterTextChanged(Editable s) {
194                 checkAmountValid(s.toString());
195
196                 if (syncData())
197                     adapter.model.checkTransactionSubmittable(null);
198             }
199         };
200         b.newTransactionDescription.addTextChangedListener(tw);
201         monitorComment(b.transactionComment);
202         b.accountRowAccName.addTextChangedListener(tw);
203         monitorComment(b.comment);
204         b.accountRowAccAmounts.addTextChangedListener(amountWatcher);
205
206         b.currencyButton.setOnClickListener(v -> {
207             CurrencySelectorFragment cpf = new CurrencySelectorFragment();
208             cpf.showPositionAndPadding();
209             cpf.setOnCurrencySelectedListener(
210                     c -> adapter.setItemCurrency(getAdapterPosition(), c.getName()));
211             cpf.show(activity.getSupportFragmentManager(), "currency-selector");
212         });
213
214         commentFocusChanged(b.transactionComment, false);
215         commentFocusChanged(b.comment, false);
216
217         adapter.model.getFocusInfo()
218                      .observe(activity, this::applyFocus);
219
220         Data.currencyGap.observe(activity,
221                 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
222                         hasGap));
223
224         Data.currencySymbolPosition.observe(activity,
225                 position -> updateCurrencyPositionAndPadding(position,
226                         Data.currencyGap.getValue()));
227
228         adapter.model.getShowCurrency()
229                      .observe(activity, showCurrency -> {
230                          if (showCurrency) {
231                              b.currency.setVisibility(View.VISIBLE);
232                              b.currencyButton.setVisibility(View.VISIBLE);
233                              setCurrencyString(mProfile.getDefaultCommodity());
234                          }
235                          else {
236                              b.currency.setVisibility(View.GONE);
237                              b.currencyButton.setVisibility(View.GONE);
238                              setCurrencyString(null);
239                          }
240                      });
241
242         adapter.model.getShowComments()
243                      .observe(activity, show -> {
244                          ConstraintLayout.LayoutParams amountLayoutParams =
245                                  (ConstraintLayout.LayoutParams) b.amountLayout.getLayoutParams();
246                          ConstraintLayout.LayoutParams accountParams =
247                                  (ConstraintLayout.LayoutParams) b.accountRowAccName.getLayoutParams();
248
249                          if (show) {
250                              accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
251                              accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
252
253                              amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
254                              amountLayoutParams.topToBottom = b.accountRowAccName.getId();
255
256                              b.commentLayout.setVisibility(View.VISIBLE);
257                          }
258                          else {
259                              accountParams.endToStart = b.amountLayout.getId();
260                              accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
261
262                              amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
263                              amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
264
265                              b.commentLayout.setVisibility(View.GONE);
266                          }
267
268                          b.accountRowAccName.setLayoutParams(accountParams);
269                          b.amountLayout.setLayoutParams(amountLayoutParams);
270
271                          b.transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
272                      });
273     }
274     private void applyFocus(NewTransactionModel.FocusInfo focusInfo) {
275         if (ignoreFocusChanges) {
276             Logger.debug("new-trans", "Ignoring focus change");
277             return;
278         }
279         ignoreFocusChanges = true;
280         try {
281             if (((focusInfo == null) || (focusInfo.element == null) ||
282                  focusInfo.position != getAdapterPosition()))
283                 return;
284
285             NewTransactionModel.Item item = getItem();
286             if (item instanceof NewTransactionModel.TransactionHead) {
287                 NewTransactionModel.TransactionHead head = item.toTransactionHead();
288                 // bad idea - double pop-up, and not really necessary.
289                 // the user can tap the input to get the calendar
290                 //if (!tvDate.hasFocus()) tvDate.requestFocus();
291                 switch (focusInfo.element) {
292                     case TransactionComment:
293                         b.transactionComment.setVisibility(View.VISIBLE);
294                         b.transactionComment.requestFocus();
295                         break;
296                     case Description:
297                         boolean focused = b.newTransactionDescription.requestFocus();
298 //                            tvDescription.dismissDropDown();
299                         if (focused)
300                             Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
301                                                                             .getContext());
302                         break;
303                 }
304             }
305             else if (item instanceof NewTransactionModel.TransactionAccount) {
306                 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
307                 switch (focusInfo.element) {
308                     case Amount:
309                         b.accountRowAccAmounts.requestFocus();
310                         break;
311                     case Comment:
312                         b.comment.setVisibility(View.VISIBLE);
313                         b.comment.requestFocus();
314                         break;
315                     case Account:
316                         boolean focused = b.accountRowAccName.requestFocus();
317 //                                         b.accountRowAccName.dismissDropDown();
318                         if (focused)
319                             Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
320                                                                             .getContext());
321                         break;
322                 }
323             }
324         }
325         finally {
326             ignoreFocusChanges = false;
327         }
328     }
329     public void checkAmountValid(String s) {
330         boolean valid = true;
331         try {
332             if (s.length() > 0) {
333                 float ignored = Float.parseFloat(s.replace(decimalSeparator, decimalDot));
334             }
335         }
336         catch (NumberFormatException ex) {
337             valid = false;
338         }
339
340         displayAmountValidity(valid);
341     }
342     private void displayAmountValidity(boolean valid) {
343         b.accountRowAccAmounts.setCompoundDrawablesRelativeWithIntrinsicBounds(
344                 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
345         b.accountRowAccAmounts.setMinEms(valid ? 4 : 5);
346     }
347     private void monitorComment(EditText editText) {
348         editText.addTextChangedListener(new TextWatcher() {
349             @Override
350             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
351             }
352             @Override
353             public void onTextChanged(CharSequence s, int start, int before, int count) {
354             }
355             @Override
356             public void afterTextChanged(Editable s) {
357 //                debug("input", "text changed");
358                 if (inUpdate)
359                     return;
360
361                 Logger.debug("textWatcher", "calling syncData()");
362                 syncData();
363                 Logger.debug("textWatcher",
364                         "syncData() returned, checking if transaction is submittable");
365                 styleComment(editText, s.toString());
366                 Logger.debug("textWatcher", "done");
367             }
368         });
369     }
370     private void commentFocusChanged(TextView textView, boolean hasFocus) {
371         @ColorInt int textColor;
372         textColor = b.dummyText.getTextColors()
373                                .getDefaultColor();
374         if (hasFocus) {
375             textView.setTypeface(null, Typeface.NORMAL);
376             textView.setHint(R.string.transaction_account_comment_hint);
377         }
378         else {
379             int alpha = (textColor >> 24 & 0xff);
380             alpha = 3 * alpha / 4;
381             textColor = (alpha << 24) | (0x00ffffff & textColor);
382             textView.setTypeface(null, Typeface.ITALIC);
383             textView.setHint("");
384             if (TextUtils.isEmpty(textView.getText())) {
385                 textView.setVisibility(View.INVISIBLE);
386             }
387         }
388         textView.setTextColor(textColor);
389
390     }
391     private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
392         ConstraintLayout.LayoutParams amountLP =
393                 (ConstraintLayout.LayoutParams) b.accountRowAccAmounts.getLayoutParams();
394         ConstraintLayout.LayoutParams currencyLP =
395                 (ConstraintLayout.LayoutParams) b.currency.getLayoutParams();
396
397         if (position == Currency.Position.before) {
398             currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
399             currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
400
401             amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
402             amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
403             amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
404             amountLP.startToEnd = b.currency.getId();
405
406             b.currency.setGravity(Gravity.END);
407         }
408         else {
409             currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
410             currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
411
412             amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
413             amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
414             amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
415             amountLP.endToStart = b.currency.getId();
416
417             b.currency.setGravity(Gravity.START);
418         }
419
420         amountLP.resolveLayoutDirection(b.accountRowAccAmounts.getLayoutDirection());
421         currencyLP.resolveLayoutDirection(b.currency.getLayoutDirection());
422
423         b.accountRowAccAmounts.setLayoutParams(amountLP);
424         b.currency.setLayoutParams(currencyLP);
425
426         // distance between the amount and the currency symbol
427         int gapSize = DimensionUtils.sp2px(b.currency.getContext(), 5);
428
429         if (position == Currency.Position.before) {
430             b.currency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
431         }
432         else {
433             b.currency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
434         }
435     }
436     private void setCurrencyString(String currency) {
437         @ColorInt int textColor = b.dummyText.getTextColors()
438                                              .getDefaultColor();
439         if (TextUtils.isEmpty(currency)) {
440             b.currency.setText(R.string.currency_symbol);
441             int alpha = (textColor >> 24) & 0xff;
442             alpha = alpha * 3 / 4;
443             b.currency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
444         }
445         else {
446             b.currency.setText(currency);
447             b.currency.setTextColor(textColor);
448         }
449     }
450     private void setCurrency(Currency currency) {
451         setCurrencyString((currency == null) ? null : currency.getName());
452     }
453     private void setEditable(Boolean editable) {
454         b.newTransactionDate.setEnabled(editable);
455         b.newTransactionDescription.setEnabled(editable);
456         b.accountRowAccName.setEnabled(editable);
457         b.accountRowAccAmounts.setEnabled(editable);
458     }
459     private void beginUpdates() {
460         if (inUpdate)
461             throw new RuntimeException("Already in update mode");
462         inUpdate = true;
463     }
464     private void endUpdates() {
465         if (!inUpdate)
466             throw new RuntimeException("Not in update mode");
467         inUpdate = false;
468     }
469     /**
470      * syncData()
471      * <p>
472      * Stores the data from the UI elements into the model item
473      * Returns true if there were changes made that suggest transaction has to be
474      * checked for being submittable
475      */
476     private boolean syncData() {
477         if (syncingData) {
478             Logger.debug("new-trans", "skipping syncData() loop");
479             return false;
480         }
481
482         NewTransactionModel.Item item = getItem();
483
484         syncingData = true;
485
486         boolean significantChange = false;
487
488         try {
489             if (item instanceof NewTransactionModel.TransactionHead) {
490                 NewTransactionModel.TransactionHead head = item.toTransactionHead();
491
492                 head.setDate(String.valueOf(b.newTransactionDate.getText()));
493
494                 // transaction description is required
495                 if (TextUtils.isEmpty(head.getDescription()) !=
496                     TextUtils.isEmpty(b.newTransactionDescription.getText()))
497                     significantChange = true;
498
499                 head.setDescription(String.valueOf(b.newTransactionDescription.getText()));
500                 head.setComment(String.valueOf(b.transactionComment.getText()));
501             }
502             else if (item instanceof NewTransactionModel.TransactionAccount) {
503                 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
504
505                 // having account name is important
506                 final Editable incomingAccountName = b.accountRowAccName.getText();
507                 if (TextUtils.isEmpty(acc.getAccountName()) !=
508                     TextUtils.isEmpty(incomingAccountName))
509                     significantChange = true;
510
511                 acc.setAccountName(String.valueOf(incomingAccountName));
512                 final int accNameSelEnd = b.accountRowAccName.getSelectionEnd();
513                 final int accNameSelStart = b.accountRowAccName.getSelectionStart();
514                 acc.setAccountNameCursorPosition(accNameSelEnd);
515
516                 acc.setComment(String.valueOf(b.comment.getText()));
517
518                 String amount = String.valueOf(b.accountRowAccAmounts.getText());
519                 amount = amount.trim();
520
521                 if (amount.isEmpty()) {
522                     if (acc.isAmountSet())
523                         significantChange = true;
524                     acc.resetAmount();
525                     acc.setAmountValid(true);
526                 }
527                 else {
528                     try {
529                         amount = amount.replace(decimalSeparator, decimalDot);
530                         final float parsedAmount = Float.parseFloat(amount);
531                         if (!acc.isAmountSet() || !Misc.equalFloats(parsedAmount, acc.getAmount()))
532                             significantChange = true;
533                         acc.setAmount(parsedAmount);
534                         acc.setAmountValid(true);
535                     }
536                     catch (NumberFormatException e) {
537                         Logger.debug("new-trans", String.format(
538                                 "assuming amount is not set due to number format exception. " +
539                                 "input was '%s'", amount));
540                         if (acc.isAmountValid())
541                             significantChange = true;
542                         acc.setAmountValid(false);
543                     }
544                     final String curr = String.valueOf(b.currency.getText());
545                     final String currValue;
546                     if (curr.equals(b.currency.getContext()
547                                               .getResources()
548                                               .getString(R.string.currency_symbol)) ||
549                         curr.isEmpty())
550                         currValue = null;
551                     else
552                         currValue = curr;
553
554                     if (!significantChange && !TextUtils.equals(acc.getCurrency(), currValue))
555                         significantChange = true;
556                     acc.setCurrency(currValue);
557                 }
558             }
559             else {
560                 throw new RuntimeException("Should not happen");
561             }
562
563             return significantChange;
564         }
565         catch (ParseException e) {
566             throw new RuntimeException("Should not happen", e);
567         }
568         finally {
569             syncingData = false;
570         }
571     }
572     private void pickTransactionDate() {
573         DatePickerFragment picker = new DatePickerFragment();
574         picker.setFutureDates(mProfile.getFutureDates());
575         picker.setOnDatePickedListener(this);
576         picker.setCurrentDateFromText(b.newTransactionDate.getText());
577         picker.show(((NewTransactionActivity) b.getRoot()
578                                                .getContext()).getSupportFragmentManager(), null);
579     }
580     /**
581      * bind
582      *
583      * @param item updates the UI elements with the data from the model item
584      */
585     @SuppressLint("DefaultLocale")
586     public void bind(@NonNull NewTransactionModel.Item item) {
587         beginUpdates();
588         try {
589             syncingData = true;
590             try {
591                 if (item instanceof NewTransactionModel.TransactionHead) {
592                     NewTransactionModel.TransactionHead head = item.toTransactionHead();
593                     b.newTransactionDate.setText(head.getFormattedDate());
594
595                     // avoid triggering completion pop-up
596                     SimpleCursorAdapter a =
597                             (SimpleCursorAdapter) b.newTransactionDescription.getAdapter();
598                     try {
599                         b.newTransactionDescription.setAdapter(null);
600                         b.newTransactionDescription.setText(head.getDescription());
601                     }
602                     finally {
603                         b.newTransactionDescription.setAdapter(a);
604                     }
605
606                     b.transactionComment.setText(head.getComment());
607                     //styleComment(b.transactionComment, head.getComment());
608
609                     b.ntrData.setVisibility(View.VISIBLE);
610                     b.ntrAccount.setVisibility(View.GONE);
611                     setEditable(true);
612                 }
613                 else if (item instanceof NewTransactionModel.TransactionAccount) {
614                     NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
615
616                     final String incomingAccountName = acc.getAccountName();
617                     final String presentAccountName = String.valueOf(b.accountRowAccName.getText());
618                     if (!TextUtils.equals(incomingAccountName, presentAccountName)) {
619                         Logger.debug("bind",
620                                 String.format("Setting account name from '%s' to '%s' (| @ %d)",
621                                         presentAccountName, incomingAccountName,
622                                         acc.getAccountNameCursorPosition()));
623                         // avoid triggering completion pop-up
624                         AccountAutocompleteAdapter a =
625                                 (AccountAutocompleteAdapter) b.accountRowAccName.getAdapter();
626                         try {
627                             b.accountRowAccName.setAdapter(null);
628                             b.accountRowAccName.setText(incomingAccountName);
629                             b.accountRowAccName.setSelection(acc.getAccountNameCursorPosition());
630                         }
631                         finally {
632                             b.accountRowAccName.setAdapter(a);
633                         }
634                     }
635
636                     final String amountHint = acc.getAmountHint();
637                     if (amountHint == null) {
638                         b.accountRowAccAmounts.setHint(R.string.zero_amount);
639                     }
640                     else {
641                         b.accountRowAccAmounts.setHint(amountHint);
642                     }
643
644                     b.accountRowAccAmounts.setImeOptions(
645                             acc.isLast() ? EditorInfo.IME_ACTION_DONE : EditorInfo.IME_ACTION_NEXT);
646
647                     setCurrencyString(acc.getCurrency());
648                     b.accountRowAccAmounts.setText(
649                             acc.isAmountSet() ? String.format("%4.2f", acc.getAmount()) : null);
650                     displayAmountValidity(true);
651
652                     b.comment.setText(acc.getComment());
653
654                     b.ntrData.setVisibility(View.GONE);
655                     b.ntrAccount.setVisibility(View.VISIBLE);
656
657                     setEditable(true);
658                 }
659                 else {
660                     throw new RuntimeException("Don't know how to handle " + item);
661                 }
662
663                 applyFocus(mAdapter.model.getFocusInfo()
664                                          .getValue());
665             }
666             finally {
667                 syncingData = false;
668             }
669         }
670         finally {
671             endUpdates();
672         }
673     }
674     private void styleComment(EditText editText, String comment) {
675         final View focusedView = editText.findFocus();
676         editText.setTypeface(null, (focusedView == editText) ? Typeface.NORMAL : Typeface.ITALIC);
677         editText.setVisibility(
678                 ((focusedView != editText) && TextUtils.isEmpty(comment)) ? View.INVISIBLE
679                                                                           : View.VISIBLE);
680     }
681     @Override
682     public void onDatePicked(int year, int month, int day) {
683         final NewTransactionModel.TransactionHead head = getItem().toTransactionHead();
684         head.setDate(new SimpleDate(year, month + 1, day));
685         b.newTransactionDate.setText(head.getFormattedDate());
686
687         boolean focused = b.newTransactionDescription.requestFocus();
688         if (focused)
689             Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
690                                                             .getContext());
691
692     }
693     private NewTransactionModel.Item getItem() {
694         return Objects.requireNonNull(mAdapter.model.getItems()
695                                                     .getValue())
696                       .get(getAdapterPosition());
697     }
698     @Override
699     public void descriptionSelected(String description) {
700         b.accountRowAccName.setText(description);
701         b.accountRowAccAmounts.requestFocus(View.FOCUS_FORWARD);
702     }
703 }