2 * Copyright © 2019 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.activity;
20 import android.annotation.SuppressLint;
21 import android.os.Build;
22 import android.text.Editable;
23 import android.text.TextWatcher;
24 import android.text.method.DigitsKeyListener;
25 import android.view.View;
26 import android.view.inputmethod.EditorInfo;
27 import android.widget.AutoCompleteTextView;
28 import android.widget.FrameLayout;
29 import android.widget.LinearLayout;
30 import android.widget.TextView;
32 import androidx.annotation.NonNull;
33 import androidx.lifecycle.Observer;
34 import androidx.recyclerview.widget.RecyclerView;
36 import net.ktnx.mobileledger.R;
37 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
38 import net.ktnx.mobileledger.model.Data;
39 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
40 import net.ktnx.mobileledger.model.MobileLedgerProfile;
41 import net.ktnx.mobileledger.ui.AutoCompleteTextViewWithClear;
42 import net.ktnx.mobileledger.ui.DatePickerFragment;
43 import net.ktnx.mobileledger.utils.Logger;
44 import net.ktnx.mobileledger.utils.MLDB;
45 import net.ktnx.mobileledger.utils.Misc;
47 import java.text.DecimalFormatSymbols;
48 import java.util.Calendar;
49 import java.util.Date;
50 import java.util.GregorianCalendar;
51 import java.util.Locale;
53 class NewTransactionItemHolder extends RecyclerView.ViewHolder
54 implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback {
55 private final String decimalSeparator;
56 private final String decimalDot;
57 private NewTransactionModel.Item item;
58 private TextView tvDate;
59 private AutoCompleteTextView tvDescription;
60 private AutoCompleteTextView tvAccount;
61 private TextView tvAmount;
62 private LinearLayout lHead;
63 private LinearLayout lAccount;
64 private FrameLayout lPadding;
65 private MobileLedgerProfile mProfile;
67 private Observer<Date> dateObserver;
68 private Observer<String> descriptionObserver;
69 private Observer<String> hintObserver;
70 private Observer<Integer> focusedAccountObserver;
71 private Observer<Integer> accountCountObserver;
72 private Observer<Boolean> editableObserver;
73 private boolean inUpdate = false;
74 private boolean syncingData = false;
75 NewTransactionItemHolder(@NonNull View itemView, NewTransactionItemsAdapter adapter) {
77 tvAccount = itemView.findViewById(R.id.account_row_acc_name);
78 tvAmount = itemView.findViewById(R.id.account_row_acc_amounts);
79 tvDate = itemView.findViewById(R.id.new_transaction_date);
80 tvDescription = itemView.findViewById(R.id.new_transaction_description);
81 lHead = itemView.findViewById(R.id.ntr_data);
82 lAccount = itemView.findViewById(R.id.ntr_account);
83 lPadding = itemView.findViewById(R.id.ntr_padding);
85 tvDescription.setNextFocusForwardId(View.NO_ID);
86 tvAccount.setNextFocusForwardId(View.NO_ID);
87 tvAmount.setNextFocusForwardId(View.NO_ID); // magic!
89 tvDate.setOnClickListener(v -> pickTransactionDate());
91 mProfile = Data.profile.getValue();
93 throw new AssertionError();
95 View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
97 boolean wasSyncing = syncingData;
100 final int pos = getAdapterPosition();
101 adapter.updateFocusedItem(pos);
102 if (v instanceof AutoCompleteTextViewWithClear) {
103 adapter.noteFocusIsOnAccount(pos);
106 adapter.noteFocusIsOnAmount(pos);
110 syncingData = wasSyncing;
115 tvDescription.setOnFocusChangeListener(focusMonitor);
116 tvAccount.setOnFocusChangeListener(focusMonitor);
117 tvAmount.setOnFocusChangeListener(focusMonitor);
119 MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
120 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
121 MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
122 "name", true, this, mProfile);
124 // FIXME: react on configuration (locale) changes
125 decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
126 .getMonetaryDecimalSeparator());
129 final TextWatcher tw = new TextWatcher() {
131 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
135 public void onTextChanged(CharSequence s, int start, int before, int count) {
139 public void afterTextChanged(Editable s) {
140 // debug("input", "text changed");
144 Logger.debug("textWatcher", "calling syncData()");
146 Logger.debug("textWatcher",
147 "syncData() returned, checking if transaction is submittable");
148 adapter.model.checkTransactionSubmittable(adapter);
149 Logger.debug("textWatcher", "done");
152 final TextWatcher amountWatcher = new TextWatcher() {
154 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
157 public void onTextChanged(CharSequence s, int start, int before, int count) {
161 public void afterTextChanged(Editable s) {
162 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
163 // only one decimal separator is allowed
164 // plus and minus are allowed only at the beginning
165 String val = s.toString();
167 tvAmount.setKeyListener(DigitsKeyListener.getInstance(
168 "0123456789+-" + decimalSeparator + decimalDot));
169 else if (val.contains(decimalSeparator) || val.contains(decimalDot))
170 tvAmount.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
172 tvAmount.setKeyListener(DigitsKeyListener.getInstance(
173 "0123456789" + decimalSeparator + decimalDot));
176 adapter.model.checkTransactionSubmittable(adapter);
180 tvDescription.addTextChangedListener(tw);
181 tvAccount.addTextChangedListener(tw);
182 tvAmount.addTextChangedListener(amountWatcher);
184 // FIXME: react on locale changes
185 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
186 tvAmount.setKeyListener(DigitsKeyListener.getInstance(Locale.getDefault(), true, true));
188 tvAmount.setKeyListener(
189 DigitsKeyListener.getInstance("0123456789+-" + decimalSeparator + decimalDot));
191 dateObserver = date -> {
196 tvDate.setText(item.getFormattedDate());
202 descriptionObserver = description -> {
207 tvDescription.setText(description);
213 hintObserver = hint -> {
219 tvAmount.setHint(R.string.zero_amount);
221 tvAmount.setHint(hint);
227 editableObserver = this::setEditable;
228 focusedAccountObserver = index -> {
229 if ((index != null) && index.equals(getAdapterPosition())) {
230 switch (item.getType()) {
232 // bad idea - double pop-up, and not really necessary.
233 // the user can tap the input to get the calendar
234 //if (!tvDate.hasFocus()) tvDate.requestFocus();
235 boolean focused = tvDescription.requestFocus();
236 tvDescription.dismissDropDown();
238 Misc.showSoftKeyboard(
239 (NewTransactionActivity) tvDescription.getContext());
242 // do nothing if a row element already has the focus
243 if (!itemView.hasFocus()) {
244 if (item.focusIsOnAmount()) {
245 tvAmount.requestFocus();
248 focused = tvAccount.requestFocus();
249 tvAccount.dismissDropDown();
251 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
259 accountCountObserver = count -> {
260 final int adapterPosition = getAdapterPosition();
261 final int layoutPosition = getLayoutPosition();
262 Logger.debug("holder",
263 String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
264 adapterPosition, layoutPosition, item.getType()
266 .concat(item.getType() ==
267 NewTransactionModel.ItemType.transactionRow
268 ? String.format(Locale.US,
274 ? String.format(Locale.US,
279 if (adapterPosition == count)
280 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
282 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
285 private void setEditable(Boolean editable) {
286 tvDate.setEnabled(editable);
287 tvDescription.setEnabled(editable);
288 tvAccount.setEnabled(editable);
289 tvAmount.setEnabled(editable);
291 private void beginUpdates() {
293 throw new RuntimeException("Already in update mode");
296 private void endUpdates() {
298 throw new RuntimeException("Not in update mode");
304 * Stores the data from the UI elements into the model item
306 private void syncData() {
311 Logger.debug("new-trans", "skipping syncData() loop");
318 switch (item.getType()) {
320 item.setDate(String.valueOf(tvDate.getText()));
321 item.setDescription(String.valueOf(tvDescription.getText()));
325 .setAccountName(String.valueOf(tvAccount.getText()));
327 // TODO: handle multiple amounts
328 String amount = String.valueOf(tvAmount.getText());
329 amount = amount.trim();
331 if (amount.isEmpty()) {
337 amount = amount.replace(decimalSeparator, decimalDot);
339 .setAmount(Float.parseFloat(amount));
341 catch (NumberFormatException e) {
342 Logger.debug("new-trans", String.format(
343 "assuming amount is not set due to number format exception. " +
344 "input was '%s'", amount));
352 throw new RuntimeException("Should not happen");
359 private void pickTransactionDate() {
360 DatePickerFragment picker = new DatePickerFragment();
361 picker.setOnDatePickedListener(this);
362 picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
368 * @param item updates the UI elements with the data from the model item
370 @SuppressLint("DefaultLocale")
371 public void setData(NewTransactionModel.Item item) {
374 if (this.item != null && !this.item.equals(item)) {
375 this.item.stopObservingDate(dateObserver);
376 this.item.stopObservingDescription(descriptionObserver);
377 this.item.stopObservingAmountHint(hintObserver);
378 this.item.stopObservingEditableFlag(editableObserver);
380 .stopObservingFocusedItem(focusedAccountObserver);
382 .stopObservingAccountCount(accountCountObserver);
387 switch (item.getType()) {
389 tvDate.setText(item.getFormattedDate());
390 tvDescription.setText(item.getDescription());
391 lHead.setVisibility(View.VISIBLE);
392 lAccount.setVisibility(View.GONE);
393 lPadding.setVisibility(View.GONE);
397 LedgerTransactionAccount acc = item.getAccount();
398 tvAccount.setText(acc.getAccountName());
399 if (acc.isAmountSet()) {
400 tvAmount.setText(String.format("%1.2f", acc.getAmount()));
403 tvAmount.setText("");
404 // tvAmount.setHint(R.string.zero_amount);
406 tvAmount.setHint(item.getAmountHint());
407 lHead.setVisibility(View.GONE);
408 lAccount.setVisibility(View.VISIBLE);
409 lPadding.setVisibility(View.GONE);
413 lHead.setVisibility(View.GONE);
414 lAccount.setVisibility(View.GONE);
415 lPadding.setVisibility(View.VISIBLE);
420 if (this.item == null) { // was null or has changed
422 final NewTransactionActivity activity =
423 (NewTransactionActivity) tvDescription.getContext();
424 item.observeDate(activity, dateObserver);
425 item.observeDescription(activity, descriptionObserver);
426 item.observeAmountHint(activity, hintObserver);
427 item.observeEditableFlag(activity, editableObserver);
429 .observeFocusedItem(activity, focusedAccountObserver);
431 .observeAccountCount(activity, accountCountObserver);
439 public void onDatePicked(int year, int month, int day) {
440 final Calendar c = GregorianCalendar.getInstance();
441 c.set(year, month, day);
442 item.setDate(c.getTime());
443 boolean focused = tvDescription.requestFocus();
445 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
449 public void descriptionSelected(String description) {
450 tvAccount.setText(description);
451 tvAmount.requestFocus(View.FOCUS_FORWARD);