]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
better shadow under main header in dark mode
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / MainActivity.java
1 /*
2  * Copyright © 2020 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.activity;
19
20 import android.content.Intent;
21 import android.content.SharedPreferences;
22 import android.content.pm.PackageInfo;
23 import android.content.pm.ShortcutInfo;
24 import android.content.pm.ShortcutManager;
25 import android.content.res.ColorStateList;
26 import android.graphics.Color;
27 import android.graphics.drawable.Icon;
28 import android.os.Build;
29 import android.os.Bundle;
30 import android.util.Log;
31 import android.view.View;
32 import android.view.ViewGroup;
33 import android.view.animation.AnimationUtils;
34 import android.widget.LinearLayout;
35 import android.widget.ProgressBar;
36 import android.widget.TextView;
37
38 import androidx.annotation.NonNull;
39 import androidx.appcompat.app.ActionBarDrawerToggle;
40 import androidx.appcompat.widget.Toolbar;
41 import androidx.core.view.GravityCompat;
42 import androidx.drawerlayout.widget.DrawerLayout;
43 import androidx.fragment.app.Fragment;
44 import androidx.fragment.app.FragmentManager;
45 import androidx.fragment.app.FragmentPagerAdapter;
46 import androidx.lifecycle.ViewModelProvider;
47 import androidx.recyclerview.widget.LinearLayoutManager;
48 import androidx.recyclerview.widget.RecyclerView;
49 import androidx.viewpager.widget.ViewPager;
50
51 import com.google.android.material.floatingactionbutton.FloatingActionButton;
52 import com.google.android.material.snackbar.Snackbar;
53
54 import net.ktnx.mobileledger.R;
55 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
56 import net.ktnx.mobileledger.model.Data;
57 import net.ktnx.mobileledger.model.MobileLedgerProfile;
58 import net.ktnx.mobileledger.ui.MainModel;
59 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
60 import net.ktnx.mobileledger.ui.profiles.ProfileDetailFragment;
61 import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
62 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
63 import net.ktnx.mobileledger.utils.Colors;
64 import net.ktnx.mobileledger.utils.Logger;
65 import net.ktnx.mobileledger.utils.MLDB;
66
67 import org.jetbrains.annotations.NotNull;
68
69 import java.text.DateFormat;
70 import java.util.ArrayList;
71 import java.util.Date;
72 import java.util.List;
73 import java.util.Locale;
74
75 /*
76  * TODO: reports
77  *  */
78
79 public class MainActivity extends ProfileThemedActivity {
80     public static final String STATE_CURRENT_PAGE = "current_page";
81     public static final String BUNDLE_SAVED_STATE = "bundle_savedState";
82     public static final String STATE_ACC_FILTER = "account_filter";
83     private static final String PREF_THEME_ID = "themeId";
84     DrawerLayout drawer;
85     private View profileListHeadMore, profileListHeadCancel, profileListHeadAddProfile;
86     private View bTransactionListCancelDownload;
87     private SectionsPagerAdapter mSectionsPagerAdapter;
88     private ViewPager mViewPager;
89     private FloatingActionButton fab;
90     private ProfilesRecyclerViewAdapter mProfileListAdapter;
91     private int mCurrentPage;
92     private boolean mBackMeansToAccountList = false;
93     private Toolbar mToolbar;
94     private DrawerLayout.SimpleDrawerListener drawerListener;
95     private ActionBarDrawerToggle barDrawerToggle;
96     private ViewPager.SimpleOnPageChangeListener pageChangeListener;
97     private MobileLedgerProfile profile;
98     private MainModel mainModel;
99     @Override
100     protected void onStart() {
101         super.onStart();
102
103         Logger.debug("MainActivity", "onStart()");
104
105         mViewPager.setCurrentItem(mCurrentPage, false);
106     }
107     @Override
108     protected void onSaveInstanceState(@NotNull Bundle outState) {
109         super.onSaveInstanceState(outState);
110         outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
111         if (mainModel.getAccountFilter()
112                      .getValue() != null)
113             outState.putString(STATE_ACC_FILTER, mainModel.getAccountFilter()
114                                                           .getValue());
115     }
116     @Override
117     protected void onDestroy() {
118         mSectionsPagerAdapter = null;
119         RecyclerView root = findViewById(R.id.nav_profile_list);
120         if (root != null)
121             root.setAdapter(null);
122         if (drawer != null)
123             drawer.removeDrawerListener(drawerListener);
124         drawerListener = null;
125         if (drawer != null)
126             drawer.removeDrawerListener(barDrawerToggle);
127         barDrawerToggle = null;
128         if (mViewPager != null)
129             mViewPager.removeOnPageChangeListener(pageChangeListener);
130         pageChangeListener = null;
131         super.onDestroy();
132     }
133     @Override
134     protected void setupProfileColors() {
135         SharedPreferences prefs = getPreferences(MODE_PRIVATE);
136         int profileColor = prefs.getInt(PREF_THEME_ID, -2);
137         if (profileColor == -2)
138             profileColor = Data.retrieveCurrentThemeIdFromDb();
139         Colors.setupTheme(this, profileColor);
140         Colors.profileThemeId = profileColor;
141         storeThemeIdInPrefs(profileColor);
142     }
143     @Override
144     protected void onResume() {
145         super.onResume();
146         fabShouldShow();
147     }
148     @Override
149     protected void onCreate(Bundle savedInstanceState) {
150         Logger.debug("MainActivity", "onCreate()/entry");
151         super.onCreate(savedInstanceState);
152         Logger.debug("MainActivity", "onCreate()/after super");
153         setContentView(R.layout.activity_main);
154
155         mainModel = new ViewModelProvider(this).get(MainModel.class);
156
157         fab = findViewById(R.id.btn_add_transaction);
158         profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
159         profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
160         LinearLayout profileListHeadMoreAndCancel =
161                 findViewById(R.id.nav_profile_list_head_buttons);
162         profileListHeadAddProfile = findViewById(R.id.nav_new_profile_button);
163         drawer = findViewById(R.id.drawer_layout);
164         bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
165         mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
166         mViewPager = findViewById(R.id.root_frame);
167
168         Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
169         if (extra != null && savedInstanceState == null)
170             savedInstanceState = extra;
171
172
173         mToolbar = findViewById(R.id.toolbar);
174         setSupportActionBar(mToolbar);
175
176         Data.observeProfile(this, this::onProfileChanged);
177
178         Data.profiles.observe(this, this::onProfileListChanged);
179         Data.backgroundTaskProgress.observe(this, this::onRetrieveProgress);
180         Data.backgroundTasksRunning.observe(this, this::onRetrieveRunningChanged);
181
182         if (barDrawerToggle == null) {
183             barDrawerToggle = new ActionBarDrawerToggle(this, drawer, mToolbar,
184                     R.string.navigation_drawer_open, R.string.navigation_drawer_close);
185             drawer.addDrawerListener(barDrawerToggle);
186         }
187         barDrawerToggle.syncState();
188
189         try {
190             PackageInfo pi = getApplicationContext().getPackageManager()
191                                                     .getPackageInfo(getPackageName(), 0);
192             ((TextView) findViewById(R.id.nav_upper).findViewById(
193                     R.id.drawer_version_text)).setText(pi.versionName);
194             ((TextView) findViewById(R.id.no_profiles_layout).findViewById(
195                     R.id.drawer_version_text)).setText(pi.versionName);
196         }
197         catch (Exception e) {
198             e.printStackTrace();
199         }
200
201         markDrawerItemCurrent(R.id.nav_account_summary);
202
203         mViewPager.setAdapter(mSectionsPagerAdapter);
204
205         if (pageChangeListener == null) {
206             pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
207                 @Override
208                 public void onPageSelected(int position) {
209                     mCurrentPage = position;
210                     switch (position) {
211                         case 0:
212                             markDrawerItemCurrent(R.id.nav_account_summary);
213                             break;
214                         case 1:
215                             markDrawerItemCurrent(R.id.nav_latest_transactions);
216                             break;
217                         default:
218                             Log.e("MainActivity",
219                                     String.format("Unexpected page index %d", position));
220                     }
221
222                     super.onPageSelected(position);
223                 }
224             };
225             mViewPager.addOnPageChangeListener(pageChangeListener);
226         }
227
228         mCurrentPage = 0;
229         if (savedInstanceState != null) {
230             int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
231             if (currentPage != -1) {
232                 mCurrentPage = currentPage;
233             }
234             mainModel.getAccountFilter()
235                      .setValue(savedInstanceState.getString(STATE_ACC_FILTER, null));
236         }
237
238         mainModel.lastUpdateDate.observe(this, this::updateLastUpdateDisplay);
239
240         findViewById(R.id.btn_no_profiles_add).setOnClickListener(
241                 v -> startEditProfileActivity(null));
242
243         findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
244
245         findViewById(R.id.nav_new_profile_button).setOnClickListener(
246                 v -> startEditProfileActivity(null));
247
248         RecyclerView root = findViewById(R.id.nav_profile_list);
249         if (root == null)
250             throw new RuntimeException("Can't get hold on the transaction value view");
251
252         if (mProfileListAdapter == null)
253             mProfileListAdapter = new ProfilesRecyclerViewAdapter();
254         root.setAdapter(mProfileListAdapter);
255
256         mProfileListAdapter.editingProfiles.observe(this, newValue -> {
257             if (newValue) {
258                 profileListHeadMore.setVisibility(View.GONE);
259                 profileListHeadCancel.setVisibility(View.VISIBLE);
260                 profileListHeadAddProfile.setVisibility(View.VISIBLE);
261                 if (drawer.isDrawerOpen(GravityCompat.START)) {
262                     profileListHeadMore.startAnimation(
263                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
264                     profileListHeadCancel.startAnimation(
265                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
266                     profileListHeadAddProfile.startAnimation(
267                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
268                 }
269             }
270             else {
271                 profileListHeadCancel.setVisibility(View.GONE);
272                 profileListHeadMore.setVisibility(View.VISIBLE);
273                 profileListHeadAddProfile.setVisibility(View.GONE);
274                 if (drawer.isDrawerOpen(GravityCompat.START)) {
275                     profileListHeadCancel.startAnimation(
276                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
277                     profileListHeadMore.startAnimation(
278                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
279                     profileListHeadAddProfile.startAnimation(
280                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
281                 }
282             }
283
284             mProfileListAdapter.notifyDataSetChanged();
285         });
286
287         LinearLayoutManager llm = new LinearLayoutManager(this);
288
289         llm.setOrientation(RecyclerView.VERTICAL);
290         root.setLayoutManager(llm);
291
292         profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
293         profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
294         profileListHeadMoreAndCancel.setOnClickListener(
295                 (v) -> mProfileListAdapter.flipEditingProfiles());
296         if (drawerListener == null) {
297             drawerListener = new DrawerLayout.SimpleDrawerListener() {
298                 @Override
299                 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
300                     if (slideOffset > 0.2)
301                         fabHide();
302                 }
303                 @Override
304                 public void onDrawerClosed(View drawerView) {
305                     super.onDrawerClosed(drawerView);
306                     mProfileListAdapter.setAnimationsEnabled(false);
307                     mProfileListAdapter.editingProfiles.setValue(false);
308                     Data.drawerOpen.setValue(false);
309                     fabShouldShow();
310                 }
311                 @Override
312                 public void onDrawerOpened(View drawerView) {
313                     super.onDrawerOpened(drawerView);
314                     mProfileListAdapter.setAnimationsEnabled(true);
315                     Data.drawerOpen.setValue(true);
316                     fabHide();
317                 }
318             };
319             drawer.addDrawerListener(drawerListener);
320         }
321
322         Data.drawerOpen.observe(this, open -> {
323             if (open)
324                 drawer.open();
325             else
326                 drawer.close();
327         });
328
329         mainModel.getUpdateError()
330                  .observe(this, (error) -> {
331                      if (error == null)
332                          return;
333
334                      Snackbar.make(mViewPager, error, Snackbar.LENGTH_LONG)
335                              .show();
336                      mainModel.clearUpdateError();
337                  });
338     }
339     private void scheduleDataRetrievalIfStale(long lastUpdate) {
340         long now = new Date().getTime();
341         if ((lastUpdate == 0) || (now > (lastUpdate + (24 * 3600 * 1000)))) {
342             if (lastUpdate == 0)
343                 Logger.debug("db::", "WEB data never fetched. scheduling a fetch");
344             else
345                 Logger.debug("db", String.format(Locale.ENGLISH,
346                         "WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
347                         lastUpdate / 1000f, now / 1000f));
348
349             mainModel.scheduleTransactionListRetrieval();
350         }
351     }
352     private void createShortcuts(List<MobileLedgerProfile> list) {
353         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
354             return;
355
356         ShortcutManager sm = getSystemService(ShortcutManager.class);
357         List<ShortcutInfo> shortcuts = new ArrayList<>();
358         int i = 0;
359         for (MobileLedgerProfile p : list) {
360             if (shortcuts.size() >= sm.getMaxShortcutCountPerActivity())
361                 break;
362
363             if (!p.isPostingPermitted())
364                 continue;
365
366             final ShortcutInfo.Builder builder =
367                     new ShortcutInfo.Builder(this, "new_transaction_" + p.getUuid());
368             ShortcutInfo si = builder.setShortLabel(p.getName())
369                                      .setIcon(Icon.createWithResource(this,
370                                              R.drawable.thick_plus_icon))
371                                      .setIntent(new Intent(Intent.ACTION_VIEW, null, this,
372                                              NewTransactionActivity.class).putExtra("profile_uuid",
373                                              p.getUuid()))
374                                      .setRank(i)
375                                      .build();
376             shortcuts.add(si);
377             i++;
378         }
379         sm.setDynamicShortcuts(shortcuts);
380     }
381     private void onProfileListChanged(List<MobileLedgerProfile> newList) {
382         if ((newList == null) || newList.isEmpty()) {
383             findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
384             findViewById(R.id.main_app_layout).setVisibility(View.GONE);
385             return;
386         }
387
388         findViewById(R.id.main_app_layout).setVisibility(View.VISIBLE);
389         findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
390
391         findViewById(R.id.nav_profile_list).setMinimumHeight(
392                 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
393
394         Logger.debug("profiles", "profile list changed");
395         mProfileListAdapter.notifyDataSetChanged();
396
397         createShortcuts(newList);
398     }
399     /**
400      * called when the current profile has changed
401      */
402     private void onProfileChanged(MobileLedgerProfile profile) {
403         if (this.profile == null) {
404             if (profile == null)
405                 return;
406         }
407         else {
408             if (this.profile.equals(profile))
409                 return;
410         }
411
412         boolean haveProfile = profile != null;
413
414         if (haveProfile)
415             setTitle(profile.getName());
416         else
417             setTitle(R.string.app_name);
418
419         mainModel.setProfile(profile);
420
421         this.profile = profile;
422
423         int newProfileTheme = haveProfile ? profile.getThemeHue() : -1;
424         if (newProfileTheme != Colors.profileThemeId) {
425             Logger.debug("profiles",
426                     String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
427                             newProfileTheme));
428             Colors.profileThemeId = newProfileTheme;
429             profileThemeChanged();
430             // profileThemeChanged would restart the activity, so no need to reload the
431             // data sets below
432             return;
433         }
434
435         findViewById(R.id.no_profiles_layout).setVisibility(haveProfile ? View.GONE : View.VISIBLE);
436         findViewById(R.id.pager_layout).setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
437
438         mProfileListAdapter.notifyDataSetChanged();
439
440         mainModel.clearTransactions();
441
442         if (haveProfile) {
443             mainModel.scheduleAccountListReload();
444             Logger.debug("transactions", "requesting list reload");
445             mainModel.scheduleTransactionListReload();
446
447             if (profile.isPostingPermitted()) {
448                 mToolbar.setSubtitle(null);
449                 fab.show();
450             }
451             else {
452                 mToolbar.setSubtitle(R.string.profile_subtitle_read_only);
453                 fab.hide();
454             }
455         }
456         else {
457             mToolbar.setSubtitle(null);
458             fab.hide();
459         }
460
461         updateLastUpdateTextFromDB();
462     }
463     private void updateLastUpdateDisplay(Date newValue) {
464         ViewGroup l = findViewById(R.id.transactions_last_update_layout);
465         TextView v = findViewById(R.id.transactions_last_update);
466         if (newValue == null) {
467             l.setVisibility(View.INVISIBLE);
468             Logger.debug("main", "no last update date :(");
469         }
470         else {
471             final String text = DateFormat.getDateTimeInstance()
472                                           .format(newValue);
473             v.setText(text);
474             l.setVisibility(View.VISIBLE);
475             Logger.debug("main", String.format("Date formatted: %s", text));
476         }
477     }
478     private void profileThemeChanged() {
479         storeThemeIdInPrefs(profile.getThemeHue());
480
481         // un-hook all observed LiveData
482         Data.removeProfileObservers(this);
483         Data.profiles.removeObservers(this);
484         mainModel.lastUpdateDate.removeObservers(this);
485
486         recreate();
487     }
488     private void storeThemeIdInPrefs(int themeId) {
489         // store the new theme id in the preferences
490         SharedPreferences prefs = getPreferences(MODE_PRIVATE);
491         SharedPreferences.Editor e = prefs.edit();
492         e.putInt(PREF_THEME_ID, themeId);
493         e.apply();
494     }
495     public void startEditProfileActivity(MobileLedgerProfile profile) {
496         Intent intent = new Intent(this, ProfileDetailActivity.class);
497         Bundle args = new Bundle();
498         if (profile != null) {
499             int index = Data.getProfileIndex(profile);
500             if (index != -1)
501                 intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
502         }
503         intent.putExtras(args);
504         startActivity(intent, args);
505     }
506     public void fabNewTransactionClicked(View view) {
507         Intent intent = new Intent(this, NewTransactionActivity.class);
508         startActivity(intent);
509         overridePendingTransition(R.anim.slide_in_up, R.anim.dummy);
510     }
511     public void markDrawerItemCurrent(int id) {
512         TextView item = drawer.findViewById(id);
513         item.setBackgroundColor(Colors.tableRowDarkBG);
514
515         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
516         for (int i = 0; i < actions.getChildCount(); i++) {
517             View view = actions.getChildAt(i);
518             if (view.getId() != id) {
519                 view.setBackgroundColor(Color.TRANSPARENT);
520             }
521         }
522     }
523     public void onAccountSummaryClicked(View view) {
524         drawer.closeDrawers();
525
526         showAccountSummaryFragment();
527     }
528     private void showAccountSummaryFragment() {
529         mViewPager.setCurrentItem(0, true);
530         mainModel.getAccountFilter()
531                  .setValue(null);
532     }
533     public void onLatestTransactionsClicked(View view) {
534         drawer.closeDrawers();
535
536         showTransactionsFragment(null);
537     }
538     public void showTransactionsFragment(String accName) {
539         mainModel.getAccountFilter()
540                  .setValue(accName);
541         mViewPager.setCurrentItem(1, true);
542     }
543     public void showAccountTransactions(String accountName) {
544         mBackMeansToAccountList = true;
545         showTransactionsFragment(accountName);
546     }
547     @Override
548     public void onBackPressed() {
549         DrawerLayout drawer = findViewById(R.id.drawer_layout);
550         if (drawer.isDrawerOpen(GravityCompat.START)) {
551             drawer.closeDrawer(GravityCompat.START);
552         }
553         else {
554             if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
555                 mainModel.getAccountFilter()
556                          .setValue(null);
557                 showAccountSummaryFragment();
558                 mBackMeansToAccountList = false;
559             }
560             else {
561                 Logger.debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
562                         getSupportFragmentManager().getBackStackEntryCount()));
563
564                 super.onBackPressed();
565             }
566         }
567     }
568     public void updateLastUpdateTextFromDB() {
569         if (profile == null)
570             return;
571
572         long last_update = profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
573
574         Logger.debug("transactions",
575                 String.format(Locale.ENGLISH, "Last update = %d", last_update));
576         if (last_update == 0) {
577             mainModel.lastUpdateDate.postValue(null);
578         }
579         else {
580             mainModel.lastUpdateDate.postValue(new Date(last_update));
581         }
582         scheduleDataRetrievalIfStale(last_update);
583
584     }
585     public void onStopTransactionRefreshClick(View view) {
586         Logger.debug("interactive", "Cancelling transactions refresh");
587         mainModel.stopTransactionsRetrieval();
588         bTransactionListCancelDownload.setEnabled(false);
589     }
590     public void onRetrieveRunningChanged(Boolean running) {
591         final View progressLayout = findViewById(R.id.transaction_progress_layout);
592         if (running) {
593             ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
594             bTransactionListCancelDownload.setEnabled(true);
595             ColorStateList csl = Colors.getColorStateList();
596             progressBar.setIndeterminateTintList(csl);
597             progressBar.setProgressTintList(csl);
598             progressBar.setIndeterminate(true);
599             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
600                 progressBar.setProgress(0, false);
601             }
602             else {
603                 progressBar.setProgress(0);
604             }
605             progressLayout.setVisibility(View.VISIBLE);
606         }
607         else {
608             progressLayout.setVisibility(View.GONE);
609         }
610     }
611     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
612         ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
613
614         if (progress.getState() == RetrieveTransactionsTask.ProgressState.FINISHED) {
615             Logger.debug("progress", "Done");
616             findViewById(R.id.transaction_progress_layout).setVisibility(View.GONE);
617
618             mainModel.transactionRetrievalDone();
619
620             if (progress.getError() != null) {
621                 Snackbar.make(mViewPager, progress.getError(), Snackbar.LENGTH_LONG)
622                         .show();
623                 return;
624             }
625
626             return;
627         }
628
629
630         bTransactionListCancelDownload.setEnabled(true);
631 //        ColorStateList csl = Colors.getColorStateList();
632 //        progressBar.setIndeterminateTintList(csl);
633 //        progressBar.setProgressTintList(csl);
634 //        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
635 //            progressBar.setProgress(0, false);
636 //        else
637 //            progressBar.setProgress(0);
638         findViewById(R.id.transaction_progress_layout).setVisibility(View.VISIBLE);
639
640         if (progress.isIndeterminate() || (progress.getTotal() <= 0)) {
641             progressBar.setIndeterminate(true);
642             Logger.debug("progress", "indeterminate");
643         }
644         else {
645             if (progressBar.isIndeterminate()) {
646                 progressBar.setIndeterminate(false);
647             }
648 //            Logger.debug("progress",
649 //                    String.format(Locale.US, "%d/%d", progress.getProgress(), progress.getTotal
650 //                    ()));
651             progressBar.setMax(progress.getTotal());
652             // for some reason animation doesn't work - no progress is shown (stick at 0)
653             // on lineageOS 14.1 (Nougat, 7.1.2)
654             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
655                 progressBar.setProgress(progress.getProgress(), false);
656             else
657                 progressBar.setProgress(progress.getProgress());
658         }
659     }
660     public void fabShouldShow() {
661         if ((profile != null) && profile.isPostingPermitted() && !drawer.isOpen())
662             fab.show();
663         else
664             fabHide();
665     }
666     public void fabHide() {
667         fab.hide();
668     }
669
670     public static class SectionsPagerAdapter extends FragmentPagerAdapter {
671
672         SectionsPagerAdapter(FragmentManager fm) {
673             super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
674         }
675
676         @NotNull
677         @Override
678         public Fragment getItem(int position) {
679             Logger.debug("main",
680                     String.format(Locale.ENGLISH, "Switching to fragment %d", position));
681             switch (position) {
682                 case 0:
683 //                    debug("flow", "Creating account summary fragment");
684                     return new AccountSummaryFragment();
685                 case 1:
686                     return new TransactionListFragment();
687                 default:
688                     throw new IllegalStateException(
689                             String.format("Unexpected fragment index: " + "%d", position));
690             }
691         }
692
693         @Override
694         public int getCount() {
695             return 2;
696         }
697     }
698 }