Search in sources :

Example 66 with ViewModelProvider

use of androidx.lifecycle.ViewModelProvider in project Infinity-For-Reddit by Docile-Alligator.

the class PostFilterUsageListingActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    ((Infinity) getApplication()).getAppComponent().inject(this);
    setImmersiveModeNotApplicable();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post_filter_application);
    ButterKnife.bind(this);
    applyCustomTheme();
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    postFilter = getIntent().getParcelableExtra(EXTRA_POST_FILTER);
    setTitle(postFilter.name);
    fab.setOnClickListener(view -> {
        NewPostFilterUsageBottomSheetFragment newPostFilterUsageBottomSheetFragment = new NewPostFilterUsageBottomSheetFragment();
        newPostFilterUsageBottomSheetFragment.show(getSupportFragmentManager(), newPostFilterUsageBottomSheetFragment.getTag());
    });
    adapter = new PostFilterUsageRecyclerViewAdapter(this, postFilterUsage -> {
        PostFilterUsageOptionsBottomSheetFragment postFilterUsageOptionsBottomSheetFragment = new PostFilterUsageOptionsBottomSheetFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelable(PostFilterUsageOptionsBottomSheetFragment.EXTRA_POST_FILTER_USAGE, postFilterUsage);
        postFilterUsageOptionsBottomSheetFragment.setArguments(bundle);
        postFilterUsageOptionsBottomSheetFragment.show(getSupportFragmentManager(), postFilterUsageOptionsBottomSheetFragment.getTag());
    });
    recyclerView.setAdapter(adapter);
    postFilterUsageViewModel = new ViewModelProvider(this, new PostFilterUsageViewModel.Factory(redditDataRoomDatabase, postFilter.name)).get(PostFilterUsageViewModel.class);
    postFilterUsageViewModel.getPostFilterUsageListLiveData().observe(this, postFilterUsages -> adapter.setPostFilterUsages(postFilterUsages));
}
Also used : PostFilterUsageRecyclerViewAdapter(ml.docilealligator.infinityforreddit.adapters.PostFilterUsageRecyclerViewAdapter) Context(android.content.Context) TextInputEditText(com.google.android.material.textfield.TextInputEditText) Bundle(android.os.Bundle) PostFilter(ml.docilealligator.infinityforreddit.postfilter.PostFilter) ButterKnife(butterknife.ButterKnife) NonNull(androidx.annotation.NonNull) R(ml.docilealligator.infinityforreddit.R) MaterialAlertDialogBuilder(com.google.android.material.dialog.MaterialAlertDialogBuilder) TextInputLayout(com.google.android.material.textfield.TextInputLayout) Infinity(ml.docilealligator.infinityforreddit.Infinity) CustomThemeWrapper(ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper) AppBarLayout(com.google.android.material.appbar.AppBarLayout) PostFilterUsageRecyclerViewAdapter(ml.docilealligator.infinityforreddit.adapters.PostFilterUsageRecyclerViewAdapter) MenuItem(android.view.MenuItem) InputMethodManager(android.view.inputmethod.InputMethodManager) BindView(butterknife.BindView) ColorStateList(android.content.res.ColorStateList) Inject(javax.inject.Inject) PostFilterUsageViewModel(ml.docilealligator.infinityforreddit.postfilter.PostFilterUsageViewModel) FloatingActionButton(com.google.android.material.floatingactionbutton.FloatingActionButton) PostFilterUsage(ml.docilealligator.infinityforreddit.postfilter.PostFilterUsage) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) Named(javax.inject.Named) RedditDataRoomDatabase(ml.docilealligator.infinityforreddit.RedditDataRoomDatabase) PostFilterUsageOptionsBottomSheetFragment(ml.docilealligator.infinityforreddit.bottomsheetfragments.PostFilterUsageOptionsBottomSheetFragment) CoordinatorLayout(androidx.coordinatorlayout.widget.CoordinatorLayout) ViewModelProvider(androidx.lifecycle.ViewModelProvider) Executor(java.util.concurrent.Executor) NewPostFilterUsageBottomSheetFragment(ml.docilealligator.infinityforreddit.bottomsheetfragments.NewPostFilterUsageBottomSheetFragment) CollapsingToolbarLayout(com.google.android.material.appbar.CollapsingToolbarLayout) SharedPreferences(android.content.SharedPreferences) DeletePostFilterUsage(ml.docilealligator.infinityforreddit.postfilter.DeletePostFilterUsage) Toolbar(androidx.appcompat.widget.Toolbar) SavePostFilterUsage(ml.docilealligator.infinityforreddit.postfilter.SavePostFilterUsage) Bundle(android.os.Bundle) NewPostFilterUsageBottomSheetFragment(ml.docilealligator.infinityforreddit.bottomsheetfragments.NewPostFilterUsageBottomSheetFragment) PostFilterUsageOptionsBottomSheetFragment(ml.docilealligator.infinityforreddit.bottomsheetfragments.PostFilterUsageOptionsBottomSheetFragment) PostFilterUsageViewModel(ml.docilealligator.infinityforreddit.postfilter.PostFilterUsageViewModel) ViewModelProvider(androidx.lifecycle.ViewModelProvider)

Example 67 with ViewModelProvider

use of androidx.lifecycle.ViewModelProvider in project Infinity-For-Reddit by Docile-Alligator.

the class SubredditMultiselectionActivity method bindView.

private void bindView() {
    mLinearLayoutManager = new LinearLayoutManagerBugFixed(this);
    mRecyclerView.setLayoutManager(mLinearLayoutManager);
    mAdapter = new SubredditMultiselectionRecyclerViewAdapter(this, mCustomThemeWrapper);
    mRecyclerView.setAdapter(mAdapter);
    mSubscribedSubredditViewModel = new ViewModelProvider(this, new SubscribedSubredditViewModel.Factory(getApplication(), mRedditDataRoomDatabase, mAccountName)).get(SubscribedSubredditViewModel.class);
    mSubscribedSubredditViewModel.getAllSubscribedSubreddits().observe(this, subscribedSubredditData -> {
        mSwipeRefreshLayout.setRefreshing(false);
        if (subscribedSubredditData == null || subscribedSubredditData.size() == 0) {
            mRecyclerView.setVisibility(View.GONE);
            mLinearLayout.setVisibility(View.VISIBLE);
            mGlide.load(R.drawable.error_image).into(mImageView);
        } else {
            mLinearLayout.setVisibility(View.GONE);
            mRecyclerView.setVisibility(View.VISIBLE);
            mGlide.clear(mImageView);
        }
        mAdapter.setSubscribedSubreddits(subscribedSubredditData);
    });
}
Also used : LinearLayoutManagerBugFixed(ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed) SubredditMultiselectionRecyclerViewAdapter(ml.docilealligator.infinityforreddit.adapters.SubredditMultiselectionRecyclerViewAdapter) SubscribedSubredditViewModel(ml.docilealligator.infinityforreddit.subscribedsubreddit.SubscribedSubredditViewModel) ViewModelProvider(androidx.lifecycle.ViewModelProvider)

Example 68 with ViewModelProvider

use of androidx.lifecycle.ViewModelProvider in project Infinity-For-Reddit by Docile-Alligator.

the class MainActivity method bindView.

private void bindView() {
    if (isDestroyed()) {
        return;
    }
    if (showBottomAppBar) {
        int optionCount = mBottomAppBarSharedPreference.getInt((mAccessToken == null ? "-" : "") + SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_OPTION_COUNT, 4);
        int option1 = mBottomAppBarSharedPreference.getInt((mAccessToken == null ? "-" : "") + SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_OPTION_1, SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_OPTION_SUBSCRIPTIONS);
        int option2 = mBottomAppBarSharedPreference.getInt((mAccessToken == null ? "-" : "") + SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_OPTION_2, SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_OPTION_MULTIREDDITS);
        bottomAppBar.setVisibility(View.VISIBLE);
        if (optionCount == 2) {
            linearLayoutBottomAppBar.setWeightSum(3);
            option1BottomAppBar.setVisibility(View.GONE);
            option3BottomAppBar.setVisibility(View.GONE);
            option2BottomAppBar.setImageResource(getBottomAppBarOptionDrawableResource(option1));
            option4BottomAppBar.setImageResource(getBottomAppBarOptionDrawableResource(option2));
            option2BottomAppBar.setOnClickListener(view -> {
                bottomAppBarOptionAction(option1);
            });
            option4BottomAppBar.setOnClickListener(view -> {
                bottomAppBarOptionAction(option2);
            });
        } else {
            int option3 = mBottomAppBarSharedPreference.getInt((mAccessToken == null ? "-" : "") + SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_OPTION_3, mAccessToken == null ? SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_OPTION_REFRESH : SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_OPTION_INBOX);
            int option4 = mBottomAppBarSharedPreference.getInt((mAccessToken == null ? "-" : "") + SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_OPTION_4, mAccessToken == null ? SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_OPTION_CHANGE_SORT_TYPE : SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_OPTION_PROFILE);
            option1BottomAppBar.setImageResource(getBottomAppBarOptionDrawableResource(option1));
            option2BottomAppBar.setImageResource(getBottomAppBarOptionDrawableResource(option2));
            option3BottomAppBar.setImageResource(getBottomAppBarOptionDrawableResource(option3));
            option4BottomAppBar.setImageResource(getBottomAppBarOptionDrawableResource(option4));
            option1BottomAppBar.setOnClickListener(view -> {
                bottomAppBarOptionAction(option1);
            });
            option2BottomAppBar.setOnClickListener(view -> {
                bottomAppBarOptionAction(option2);
            });
            option3BottomAppBar.setOnClickListener(view -> {
                bottomAppBarOptionAction(option3);
            });
            option4BottomAppBar.setOnClickListener(view -> {
                bottomAppBarOptionAction(option4);
            });
        }
    } else {
        CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
        lp.setAnchorId(View.NO_ID);
        lp.gravity = Gravity.END | Gravity.BOTTOM;
        fab.setLayoutParams(lp);
    }
    fabOption = mBottomAppBarSharedPreference.getInt((mAccessToken == null ? "-" : "") + SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB, SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_SUBMIT_POSTS);
    switch(fabOption) {
        case SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_REFRESH:
            fab.setImageResource(R.drawable.ic_refresh_24dp);
            break;
        case SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_CHANGE_SORT_TYPE:
            fab.setImageResource(R.drawable.ic_sort_toolbar_24dp);
            break;
        case SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_CHANGE_POST_LAYOUT:
            fab.setImageResource(R.drawable.ic_post_layout_24dp);
            break;
        case SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_SEARCH:
            fab.setImageResource(R.drawable.ic_search_black_24dp);
            break;
        case SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_GO_TO_SUBREDDIT:
            fab.setImageResource(R.drawable.ic_subreddit_24dp);
            break;
        case SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_GO_TO_USER:
            fab.setImageResource(R.drawable.ic_user_24dp);
            break;
        case SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_RANDOM:
            fab.setImageResource(R.drawable.ic_random_24dp);
            break;
        case SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_HIDE_READ_POSTS:
            if (mAccessToken == null) {
                fab.setImageResource(R.drawable.ic_filter_24dp);
                fabOption = SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_FILTER_POSTS;
            } else {
                fab.setImageResource(R.drawable.ic_hide_read_posts_24dp);
            }
            break;
        case SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_FILTER_POSTS:
            fab.setImageResource(R.drawable.ic_filter_24dp);
            break;
        default:
            if (mAccessToken == null) {
                fab.setImageResource(R.drawable.ic_filter_24dp);
                fabOption = SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_FILTER_POSTS;
            } else {
                fab.setImageResource(R.drawable.ic_add_day_night_24dp);
            }
            break;
    }
    fab.setOnClickListener(view -> {
        switch(fabOption) {
            case SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_REFRESH:
                {
                    if (sectionsPagerAdapter != null) {
                        sectionsPagerAdapter.refresh();
                    }
                    break;
                }
            case SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_CHANGE_SORT_TYPE:
                {
                    changeSortType();
                    break;
                }
            case SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_CHANGE_POST_LAYOUT:
                {
                    PostLayoutBottomSheetFragment postLayoutBottomSheetFragment = new PostLayoutBottomSheetFragment();
                    postLayoutBottomSheetFragment.show(getSupportFragmentManager(), postLayoutBottomSheetFragment.getTag());
                    break;
                }
            case SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_SEARCH:
                {
                    Intent intent = new Intent(this, SearchActivity.class);
                    startActivity(intent);
                    break;
                }
            case SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_GO_TO_SUBREDDIT:
                goToSubreddit();
                break;
            case SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_GO_TO_USER:
                goToUser();
                break;
            case SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_RANDOM:
                randomThing();
                break;
            case SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_HIDE_READ_POSTS:
                if (sectionsPagerAdapter != null) {
                    sectionsPagerAdapter.hideReadPosts();
                }
                break;
            case SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_FAB_FILTER_POSTS:
                if (sectionsPagerAdapter != null) {
                    sectionsPagerAdapter.filterPosts();
                }
                break;
            default:
                PostTypeBottomSheetFragment postTypeBottomSheetFragment = new PostTypeBottomSheetFragment();
                postTypeBottomSheetFragment.show(getSupportFragmentManager(), postTypeBottomSheetFragment.getTag());
                break;
        }
    });
    fab.setOnLongClickListener(view -> {
        FABMoreOptionsBottomSheetFragment fabMoreOptionsBottomSheetFragment = new FABMoreOptionsBottomSheetFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean(FABMoreOptionsBottomSheetFragment.EXTRA_ANONYMOUS_MODE, mAccessToken == null);
        fabMoreOptionsBottomSheetFragment.setArguments(bundle);
        fabMoreOptionsBottomSheetFragment.show(getSupportFragmentManager(), fabMoreOptionsBottomSheetFragment.getTag());
        return true;
    });
    fab.setVisibility(View.VISIBLE);
    adapter = new NavigationDrawerRecyclerViewMergedAdapter(this, mSharedPreferences, mNsfwAndSpoilerSharedPreferences, mNavigationDrawerSharedPreferences, mCustomThemeWrapper, mAccountName, new NavigationDrawerRecyclerViewMergedAdapter.ItemClickListener() {

        @Override
        public void onMenuClick(int stringId) {
            Intent intent = null;
            if (stringId == R.string.profile) {
                intent = new Intent(MainActivity.this, ViewUserDetailActivity.class);
                intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, mAccountName);
            } else if (stringId == R.string.subscriptions) {
                if (mAccessToken != null) {
                    intent = new Intent(MainActivity.this, SubscribedThingListingActivity.class);
                } else {
                    intent = new Intent(MainActivity.this, SubscribedThingListingActivity.class);
                }
            } else if (stringId == R.string.multi_reddit) {
                intent = new Intent(MainActivity.this, SubscribedThingListingActivity.class);
                intent.putExtra(SubscribedThingListingActivity.EXTRA_SHOW_MULTIREDDITS, true);
            } else if (stringId == R.string.rpan) {
                intent = new Intent(MainActivity.this, RPANActivity.class);
            } else if (stringId == R.string.trending) {
                intent = new Intent(MainActivity.this, TrendingActivity.class);
            } else if (stringId == R.string.upvoted) {
                intent = new Intent(MainActivity.this, AccountPostsActivity.class);
                intent.putExtra(AccountPostsActivity.EXTRA_USER_WHERE, PostPagingSource.USER_WHERE_UPVOTED);
            } else if (stringId == R.string.downvoted) {
                intent = new Intent(MainActivity.this, AccountPostsActivity.class);
                intent.putExtra(AccountPostsActivity.EXTRA_USER_WHERE, PostPagingSource.USER_WHERE_DOWNVOTED);
            } else if (stringId == R.string.hidden) {
                intent = new Intent(MainActivity.this, AccountPostsActivity.class);
                intent.putExtra(AccountPostsActivity.EXTRA_USER_WHERE, PostPagingSource.USER_WHERE_HIDDEN);
            } else if (stringId == R.string.account_saved_thing_activity_label) {
                intent = new Intent(MainActivity.this, AccountSavedThingActivity.class);
            } else if (stringId == R.string.gilded) {
                intent = new Intent(MainActivity.this, AccountPostsActivity.class);
                intent.putExtra(AccountPostsActivity.EXTRA_USER_WHERE, PostPagingSource.USER_WHERE_GILDED);
            } else if (stringId == R.string.light_theme) {
                mSharedPreferences.edit().putString(SharedPreferencesUtils.THEME_KEY, "0").apply();
                AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_NO);
                mCustomThemeWrapper.setThemeType(CustomThemeSharedPreferencesUtils.LIGHT);
            } else if (stringId == R.string.dark_theme) {
                mSharedPreferences.edit().putString(SharedPreferencesUtils.THEME_KEY, "1").apply();
                AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
                if (mSharedPreferences.getBoolean(SharedPreferencesUtils.AMOLED_DARK_KEY, false)) {
                    mCustomThemeWrapper.setThemeType(CustomThemeSharedPreferencesUtils.AMOLED);
                } else {
                    mCustomThemeWrapper.setThemeType(CustomThemeSharedPreferencesUtils.DARK);
                }
            } else if (stringId == R.string.enable_nsfw) {
                if (sectionsPagerAdapter != null) {
                    mNsfwAndSpoilerSharedPreferences.edit().putBoolean((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.NSFW_BASE, true).apply();
                    sectionsPagerAdapter.changeNSFW(true);
                }
            } else if (stringId == R.string.disable_nsfw) {
                if (sectionsPagerAdapter != null) {
                    mNsfwAndSpoilerSharedPreferences.edit().putBoolean((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.NSFW_BASE, false).apply();
                    sectionsPagerAdapter.changeNSFW(false);
                }
            } else if (stringId == R.string.settings) {
                intent = new Intent(MainActivity.this, SettingsActivity.class);
            } else if (stringId == R.string.add_account) {
                Intent addAccountIntent = new Intent(MainActivity.this, LoginActivity.class);
                startActivityForResult(addAccountIntent, LOGIN_ACTIVITY_REQUEST_CODE);
            } else if (stringId == R.string.anonymous_account) {
                SwitchToAnonymousMode.switchToAnonymousMode(mRedditDataRoomDatabase, mCurrentAccountSharedPreferences, mExecutor, new Handler(), false, () -> {
                    Intent anonymousIntent = new Intent(MainActivity.this, MainActivity.class);
                    startActivity(anonymousIntent);
                    finish();
                });
            } else if (stringId == R.string.log_out) {
                SwitchToAnonymousMode.switchToAnonymousMode(mRedditDataRoomDatabase, mCurrentAccountSharedPreferences, mExecutor, new Handler(), true, () -> {
                    Intent logOutIntent = new Intent(MainActivity.this, MainActivity.class);
                    startActivity(logOutIntent);
                    finish();
                });
            }
            if (intent != null) {
                startActivity(intent);
            }
            drawer.closeDrawers();
        }

        @Override
        public void onSubscribedSubredditClick(String subredditName) {
            Intent intent = new Intent(MainActivity.this, ViewSubredditDetailActivity.class);
            intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, subredditName);
            startActivity(intent);
        }

        @Override
        public void onAccountClick(String accountName) {
            SwitchAccount.switchAccount(mRedditDataRoomDatabase, mCurrentAccountSharedPreferences, mExecutor, new Handler(), accountName, newAccount -> {
                Intent intent = new Intent(MainActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            });
        }
    });
    adapter.setInboxCount(inboxCount);
    navDrawerRecyclerView.setLayoutManager(new LinearLayoutManagerBugFixed(this));
    navDrawerRecyclerView.setAdapter(adapter.getConcatAdapter());
    int tabCount = mMainActivityTabsSharedPreferences.getInt((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_COUNT, 3);
    mShowFavoriteMultiReddits = mMainActivityTabsSharedPreferences.getBoolean((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_SHOW_FAVORITE_MULTIREDDITS, false);
    mShowMultiReddits = mMainActivityTabsSharedPreferences.getBoolean((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_SHOW_MULTIREDDITS, false);
    mShowFavoriteSubscribedSubreddits = mMainActivityTabsSharedPreferences.getBoolean((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_SHOW_FAVORITE_SUBSCRIBED_SUBREDDITS, false);
    mShowSubscribedSubreddits = mMainActivityTabsSharedPreferences.getBoolean((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_SHOW_SUBSCRIBED_SUBREDDITS, false);
    sectionsPagerAdapter = new SectionsPagerAdapter(this, tabCount, mShowFavoriteMultiReddits, mShowMultiReddits, mShowFavoriteSubscribedSubreddits, mShowSubscribedSubreddits);
    viewPager2.setAdapter(sectionsPagerAdapter);
    viewPager2.setOffscreenPageLimit(1);
    viewPager2.setUserInputEnabled(!mDisableSwipingBetweenTabs);
    if (mMainActivityTabsSharedPreferences.getBoolean((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_SHOW_TAB_NAMES, true)) {
        if (mShowFavoriteMultiReddits || mShowMultiReddits || mShowFavoriteSubscribedSubreddits || mShowSubscribedSubreddits) {
            tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        } else {
            tabLayout.setTabMode(TabLayout.MODE_FIXED);
        }
        new TabLayoutMediator(tabLayout, viewPager2, (tab, position) -> {
            switch(position) {
                case 0:
                    Utils.setTitleWithCustomFontToTab(typeface, tab, mMainActivityTabsSharedPreferences.getString((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_1_TITLE, getString(R.string.home)));
                    break;
                case 1:
                    Utils.setTitleWithCustomFontToTab(typeface, tab, mMainActivityTabsSharedPreferences.getString((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_2_TITLE, getString(R.string.popular)));
                    break;
                case 2:
                    Utils.setTitleWithCustomFontToTab(typeface, tab, mMainActivityTabsSharedPreferences.getString((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_3_TITLE, getString(R.string.all)));
                    break;
            }
            if (position >= tabCount && (mShowFavoriteMultiReddits || mShowMultiReddits || mShowFavoriteSubscribedSubreddits || mShowSubscribedSubreddits) && sectionsPagerAdapter != null) {
                if (position - tabCount < sectionsPagerAdapter.favoriteMultiReddits.size()) {
                    Utils.setTitleWithCustomFontToTab(typeface, tab, sectionsPagerAdapter.favoriteMultiReddits.get(position - tabCount).getName());
                } else if (position - tabCount - sectionsPagerAdapter.favoriteMultiReddits.size() < sectionsPagerAdapter.multiReddits.size()) {
                    Utils.setTitleWithCustomFontToTab(typeface, tab, sectionsPagerAdapter.multiReddits.get(position - tabCount - sectionsPagerAdapter.favoriteMultiReddits.size()).getName());
                } else if (position - tabCount - sectionsPagerAdapter.favoriteMultiReddits.size() - sectionsPagerAdapter.multiReddits.size() < sectionsPagerAdapter.favoriteSubscribedSubreddits.size()) {
                    Utils.setTitleWithCustomFontToTab(typeface, tab, sectionsPagerAdapter.favoriteSubscribedSubreddits.get(position - tabCount - sectionsPagerAdapter.favoriteMultiReddits.size() - sectionsPagerAdapter.multiReddits.size()).getName());
                } else if (position - tabCount - sectionsPagerAdapter.favoriteMultiReddits.size() - sectionsPagerAdapter.multiReddits.size() - sectionsPagerAdapter.favoriteSubscribedSubreddits.size() < sectionsPagerAdapter.subscribedSubreddits.size()) {
                    Utils.setTitleWithCustomFontToTab(typeface, tab, sectionsPagerAdapter.subscribedSubreddits.get(position - tabCount - sectionsPagerAdapter.favoriteMultiReddits.size() - sectionsPagerAdapter.multiReddits.size() - sectionsPagerAdapter.favoriteSubscribedSubreddits.size()).getName());
                }
            }
        }).attach();
    } else {
        tabLayout.setVisibility(View.GONE);
    }
    viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {

        @Override
        public void onPageSelected(int position) {
            if (mAccessToken != null) {
                if (showBottomAppBar) {
                    bottomAppBar.performShow();
                }
            }
            fab.show();
            sectionsPagerAdapter.displaySortTypeInToolbar();
        }
    });
    fixViewPager2Sensitivity(viewPager2);
    loadSubscriptions();
    multiRedditViewModel = new ViewModelProvider(this, new MultiRedditViewModel.Factory(getApplication(), mRedditDataRoomDatabase, mAccountName == null ? "-" : mAccountName)).get(MultiRedditViewModel.class);
    multiRedditViewModel.getAllFavoriteMultiReddits().observe(this, multiReddits -> {
        if (mShowFavoriteMultiReddits && sectionsPagerAdapter != null) {
            sectionsPagerAdapter.setFavoriteMultiReddits(multiReddits);
        }
    });
    multiRedditViewModel.getAllMultiReddits().observe(this, multiReddits -> {
        if (mShowMultiReddits && sectionsPagerAdapter != null) {
            sectionsPagerAdapter.setMultiReddits(multiReddits);
        }
    });
    subscribedSubredditViewModel = new ViewModelProvider(this, new SubscribedSubredditViewModel.Factory(getApplication(), mRedditDataRoomDatabase, mAccountName == null ? "-" : mAccountName)).get(SubscribedSubredditViewModel.class);
    subscribedSubredditViewModel.getAllSubscribedSubreddits().observe(this, subscribedSubredditData -> {
        adapter.setSubscribedSubreddits(subscribedSubredditData);
        if (mShowSubscribedSubreddits && sectionsPagerAdapter != null) {
            sectionsPagerAdapter.setSubscribedSubreddits(subscribedSubredditData);
        }
    });
    subscribedSubredditViewModel.getAllFavoriteSubscribedSubreddits().observe(this, subscribedSubredditData -> {
        adapter.setFavoriteSubscribedSubreddits(subscribedSubredditData);
        if (mShowFavoriteSubscribedSubreddits && sectionsPagerAdapter != null) {
            sectionsPagerAdapter.setFavoriteSubscribedSubreddits(subscribedSubredditData);
        }
    });
    accountViewModel = new ViewModelProvider(this, new AccountViewModel.Factory(getApplication(), mRedditDataRoomDatabase, mAccountName)).get(AccountViewModel.class);
    accountViewModel.getAccountsExceptCurrentAccountLiveData().observe(this, adapter::changeAccountsDataset);
    accountViewModel.getCurrentAccountLiveData().observe(this, account -> {
        if (account != null) {
            adapter.updateAccountInfo(account.getProfileImageUrl(), account.getBannerImageUrl(), account.getKarma());
        }
    });
    loadUserData();
    if (mAccessToken != null) {
        if (mMessageFullname != null) {
            ReadMessage.readMessage(mOauthRetrofit, mAccessToken, mMessageFullname, new ReadMessage.ReadMessageListener() {

                @Override
                public void readSuccess() {
                    mMessageFullname = null;
                }

                @Override
                public void readFailed() {
                }
            });
        }
    }
}
Also used : SwitchToAnonymousMode(ml.docilealligator.infinityforreddit.asynctasks.SwitchToAnonymousMode) Bundle(android.os.Bundle) NonNull(androidx.annotation.NonNull) Constraints(androidx.work.Constraints) R(ml.docilealligator.infinityforreddit.R) ImageView(android.widget.ImageView) Infinity(ml.docilealligator.infinityforreddit.Infinity) MarkPostAsReadInterface(ml.docilealligator.infinityforreddit.MarkPostAsReadInterface) CustomThemeWrapper(ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper) PostTypeBottomSheetFragment(ml.docilealligator.infinityforreddit.bottomsheetfragments.PostTypeBottomSheetFragment) ColorStateList(android.content.res.ColorStateList) Handler(android.os.Handler) MultiReddit(ml.docilealligator.infinityforreddit.multireddit.MultiReddit) APIUtils(ml.docilealligator.infinityforreddit.utils.APIUtils) Fragment(androidx.fragment.app.Fragment) ChangeShowAvatarOnTheRightInTheNavigationDrawerEvent(ml.docilealligator.infinityforreddit.events.ChangeShowAvatarOnTheRightInTheNavigationDrawerEvent) SubscribedUserData(ml.docilealligator.infinityforreddit.subscribeduser.SubscribedUserData) ChangeDisableSwipingBetweenTabsEvent(ml.docilealligator.infinityforreddit.events.ChangeDisableSwipingBetweenTabsEvent) ChangeNSFWEvent(ml.docilealligator.infinityforreddit.events.ChangeNSFWEvent) SortTypeSelectionCallback(ml.docilealligator.infinityforreddit.SortTypeSelectionCallback) CoordinatorLayout(androidx.coordinatorlayout.widget.CoordinatorLayout) SortType(ml.docilealligator.infinityforreddit.SortType) LinearLayoutManagerBugFixed(ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed) PostPagingSource(ml.docilealligator.infinityforreddit.post.PostPagingSource) BottomAppBar(com.google.android.material.bottomappbar.BottomAppBar) FetchSubscribedThing(ml.docilealligator.infinityforreddit.FetchSubscribedThing) RecreateActivityEvent(ml.docilealligator.infinityforreddit.events.RecreateActivityEvent) NavigationDrawerRecyclerViewMergedAdapter(ml.docilealligator.infinityforreddit.adapters.navigationdrawer.NavigationDrawerRecyclerViewMergedAdapter) Nullable(androidx.annotation.Nullable) ExistingPeriodicWorkPolicy(androidx.work.ExistingPeriodicWorkPolicy) MultiRedditViewModel(ml.docilealligator.infinityforreddit.multireddit.MultiRedditViewModel) TextWatcher(android.text.TextWatcher) NetworkType(androidx.work.NetworkType) DrawerLayout(androidx.drawerlayout.widget.DrawerLayout) RedditAPI(ml.docilealligator.infinityforreddit.apis.RedditAPI) ButterKnife(butterknife.ButterKnife) RecyclerViewContentScrollingInterface(ml.docilealligator.infinityforreddit.RecyclerViewContentScrollingInterface) SortTimeBottomSheetFragment(ml.docilealligator.infinityforreddit.bottomsheetfragments.SortTimeBottomSheetFragment) Response(retrofit2.Response) SubredditAutocompleteRecyclerViewAdapter(ml.docilealligator.infinityforreddit.adapters.SubredditAutocompleteRecyclerViewAdapter) Editable(android.text.Editable) InsertSubscribedThings(ml.docilealligator.infinityforreddit.asynctasks.InsertSubscribedThings) ArrayList(java.util.ArrayList) SubscribedSubredditData(ml.docilealligator.infinityforreddit.subscribedsubreddit.SubscribedSubredditData) PeriodicWorkRequest(androidx.work.PeriodicWorkRequest) Toast(android.widget.Toast) Menu(android.view.Menu) Post(ml.docilealligator.infinityforreddit.post.Post) Utils(ml.docilealligator.infinityforreddit.utils.Utils) Named(javax.inject.Named) FetchUserData(ml.docilealligator.infinityforreddit.user.FetchUserData) RedditDataRoomDatabase(ml.docilealligator.infinityforreddit.RedditDataRoomDatabase) FragmentManager(androidx.fragment.app.FragmentManager) SubredditData(ml.docilealligator.infinityforreddit.subreddit.SubredditData) ViewModelProvider(androidx.lifecycle.ViewModelProvider) Executor(java.util.concurrent.Executor) AppCompatDelegate(androidx.appcompat.app.AppCompatDelegate) MODE_NIGHT_NO(androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_NO) InsertReadPost(ml.docilealligator.infinityforreddit.readpost.InsertReadPost) Gravity(android.view.Gravity) SharedPreferences(android.content.SharedPreferences) Callback(retrofit2.Callback) UserData(ml.docilealligator.infinityforreddit.user.UserData) SwitchAccountEvent(ml.docilealligator.infinityforreddit.events.SwitchAccountEvent) ParseSubredditData(ml.docilealligator.infinityforreddit.subreddit.ParseSubredditData) SwitchAccount(ml.docilealligator.infinityforreddit.asynctasks.SwitchAccount) LinearLayout(android.widget.LinearLayout) MaterialAlertDialogBuilder(com.google.android.material.dialog.MaterialAlertDialogBuilder) WindowManager(android.view.WindowManager) SortTypeBottomSheetFragment(ml.docilealligator.infinityforreddit.bottomsheetfragments.SortTypeBottomSheetFragment) ChangeRequireAuthToAccountSectionEvent(ml.docilealligator.infinityforreddit.events.ChangeRequireAuthToAccountSectionEvent) AppBarLayout(com.google.android.material.appbar.AppBarLayout) BindView(butterknife.BindView) ActionBarDrawerToggle(androidx.appcompat.app.ActionBarDrawerToggle) FloatingActionButton(com.google.android.material.floatingactionbutton.FloatingActionButton) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) PostLayoutBottomSheetFragment(ml.docilealligator.infinityforreddit.bottomsheetfragments.PostLayoutBottomSheetFragment) CustomThemeSharedPreferencesUtils(ml.docilealligator.infinityforreddit.utils.CustomThemeSharedPreferencesUtils) ActivityToolbarInterface(ml.docilealligator.infinityforreddit.ActivityToolbarInterface) PostFragment(ml.docilealligator.infinityforreddit.fragments.PostFragment) TabLayout(com.google.android.material.tabs.TabLayout) FABMoreOptionsBottomSheetFragment(ml.docilealligator.infinityforreddit.bottomsheetfragments.FABMoreOptionsBottomSheetFragment) Retrofit(retrofit2.Retrofit) List(java.util.List) ChangeLockBottomAppBarEvent(ml.docilealligator.infinityforreddit.events.ChangeLockBottomAppBarEvent) MaterialToolbar(com.google.android.material.appbar.MaterialToolbar) SubscribedSubredditViewModel(ml.docilealligator.infinityforreddit.subscribedsubreddit.SubscribedSubredditViewModel) Window(android.view.Window) EditorInfo(android.view.inputmethod.EditorInfo) Call(retrofit2.Call) Context(android.content.Context) TextInputEditText(com.google.android.material.textfield.TextInputEditText) KeyEvent(android.view.KeyEvent) NavigationView(com.google.android.material.navigation.NavigationView) Intent(android.content.Intent) ViewPager2(androidx.viewpager2.widget.ViewPager2) MenuItem(android.view.MenuItem) InputMethodManager(android.view.inputmethod.InputMethodManager) FragmentActivity(androidx.fragment.app.FragmentActivity) FragmentStateAdapter(androidx.viewpager2.adapter.FragmentStateAdapter) Inject(javax.inject.Inject) EventBus(org.greenrobot.eventbus.EventBus) PullNotificationWorker(ml.docilealligator.infinityforreddit.PullNotificationWorker) WorkManager(androidx.work.WorkManager) Build(android.os.Build) MODE_NIGHT_YES(androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_YES) ActivityCompat(androidx.core.app.ActivityCompat) GravityCompat(androidx.core.view.GravityCompat) AccountViewModel(ml.docilealligator.infinityforreddit.account.AccountViewModel) CollapsingToolbarLayout(com.google.android.material.appbar.CollapsingToolbarLayout) ReadMessage(ml.docilealligator.infinityforreddit.message.ReadMessage) Color(android.graphics.Color) TimeUnit(java.util.concurrent.TimeUnit) Subscribe(org.greenrobot.eventbus.Subscribe) RandomBottomSheetFragment(ml.docilealligator.infinityforreddit.bottomsheetfragments.RandomBottomSheetFragment) SharedPreferencesUtils(ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils) Activity(android.app.Activity) TabLayoutMediator(com.google.android.material.tabs.TabLayoutMediator) LinearLayoutManagerBugFixed(ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed) PostTypeBottomSheetFragment(ml.docilealligator.infinityforreddit.bottomsheetfragments.PostTypeBottomSheetFragment) TabLayoutMediator(com.google.android.material.tabs.TabLayoutMediator) ViewPager2(androidx.viewpager2.widget.ViewPager2) AccountViewModel(ml.docilealligator.infinityforreddit.account.AccountViewModel) FABMoreOptionsBottomSheetFragment(ml.docilealligator.infinityforreddit.bottomsheetfragments.FABMoreOptionsBottomSheetFragment) NavigationDrawerRecyclerViewMergedAdapter(ml.docilealligator.infinityforreddit.adapters.navigationdrawer.NavigationDrawerRecyclerViewMergedAdapter) ViewModelProvider(androidx.lifecycle.ViewModelProvider) Bundle(android.os.Bundle) Handler(android.os.Handler) MultiRedditViewModel(ml.docilealligator.infinityforreddit.multireddit.MultiRedditViewModel) SubscribedSubredditViewModel(ml.docilealligator.infinityforreddit.subscribedsubreddit.SubscribedSubredditViewModel) Intent(android.content.Intent) CoordinatorLayout(androidx.coordinatorlayout.widget.CoordinatorLayout) ReadMessage(ml.docilealligator.infinityforreddit.message.ReadMessage) PostLayoutBottomSheetFragment(ml.docilealligator.infinityforreddit.bottomsheetfragments.PostLayoutBottomSheetFragment)

Example 69 with ViewModelProvider

use of androidx.lifecycle.ViewModelProvider in project Infinity-For-Reddit by Docile-Alligator.

the class ThemePreferenceFragment method onCreatePreferences.

@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
    setPreferencesFromResource(R.xml.theme_preferences, rootKey);
    ((Infinity) activity.getApplication()).getAppComponent().inject(this);
    if (activity.typeface != null) {
        setFont(activity.typeface);
    }
    ListPreference themePreference = findPreference(SharedPreferencesUtils.THEME_KEY);
    SwitchPreference amoledDarkSwitch = findPreference(SharedPreferencesUtils.AMOLED_DARK_KEY);
    Preference customizeLightThemePreference = findPreference(SharedPreferencesUtils.CUSTOMIZE_LIGHT_THEME);
    Preference customizeDarkThemePreference = findPreference(SharedPreferencesUtils.CUSTOMIZE_DARK_THEME);
    Preference customizeAmoledThemePreference = findPreference(SharedPreferencesUtils.CUSTOMIZE_AMOLED_THEME);
    Preference selectAndCustomizeThemePreference = findPreference(SharedPreferencesUtils.MANAGE_THEMES);
    SwitchPreference enableMaterialYouSwitchPreference = findPreference(SharedPreferencesUtils.ENABLE_MATERIAL_YOU);
    Preference applyMaterialYouPreference = findPreference(SharedPreferencesUtils.APPLY_MATERIAL_YOU);
    boolean systemDefault = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;
    if (themePreference != null && amoledDarkSwitch != null) {
        if (systemDefault) {
            themePreference.setEntries(R.array.settings_theme_q);
        } else {
            themePreference.setEntries(R.array.settings_theme);
        }
        themePreference.setOnPreferenceChangeListener((preference, newValue) -> {
            int option = Integer.parseInt((String) newValue);
            switch(option) {
                case 0:
                    AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_NO);
                    customThemeWrapper.setThemeType(CustomThemeSharedPreferencesUtils.LIGHT);
                    break;
                case 1:
                    AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
                    if (amoledDarkSwitch.isChecked()) {
                        customThemeWrapper.setThemeType(CustomThemeSharedPreferencesUtils.AMOLED);
                    } else {
                        customThemeWrapper.setThemeType(CustomThemeSharedPreferencesUtils.DARK);
                    }
                    break;
                case 2:
                    if (systemDefault) {
                        AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
                    } else {
                        AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
                    }
                    if ((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_NO) {
                        customThemeWrapper.setThemeType(CustomThemeSharedPreferencesUtils.LIGHT);
                    } else {
                        if (amoledDarkSwitch.isChecked()) {
                            customThemeWrapper.setThemeType(CustomThemeSharedPreferencesUtils.AMOLED);
                        } else {
                            customThemeWrapper.setThemeType(CustomThemeSharedPreferencesUtils.DARK);
                        }
                    }
            }
            return true;
        });
    }
    if (amoledDarkSwitch != null) {
        amoledDarkSwitch.setOnPreferenceChangeListener((preference, newValue) -> {
            if ((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_NO) {
                EventBus.getDefault().post(new RecreateActivityEvent());
                ActivityCompat.recreate(activity);
            }
            return true;
        });
    }
    if (customizeLightThemePreference != null) {
        customizeLightThemePreference.setOnPreferenceClickListener(preference -> {
            Intent intent = new Intent(activity, CustomizeThemeActivity.class);
            intent.putExtra(CustomizeThemeActivity.EXTRA_THEME_TYPE, CustomizeThemeActivity.EXTRA_LIGHT_THEME);
            startActivity(intent);
            return true;
        });
    }
    if (customizeDarkThemePreference != null) {
        customizeDarkThemePreference.setOnPreferenceClickListener(preference -> {
            Intent intent = new Intent(activity, CustomizeThemeActivity.class);
            intent.putExtra(CustomizeThemeActivity.EXTRA_THEME_TYPE, CustomizeThemeActivity.EXTRA_DARK_THEME);
            startActivity(intent);
            return true;
        });
    }
    if (customizeAmoledThemePreference != null) {
        customizeAmoledThemePreference.setOnPreferenceClickListener(preference -> {
            Intent intent = new Intent(activity, CustomizeThemeActivity.class);
            intent.putExtra(CustomizeThemeActivity.EXTRA_THEME_TYPE, CustomizeThemeActivity.EXTRA_AMOLED_THEME);
            startActivity(intent);
            return true;
        });
    }
    if (selectAndCustomizeThemePreference != null) {
        selectAndCustomizeThemePreference.setOnPreferenceClickListener(preference -> {
            Intent intent = new Intent(activity, CustomThemeListingActivity.class);
            startActivity(intent);
            return true;
        });
    }
    if (enableMaterialYouSwitchPreference != null && applyMaterialYouPreference != null) {
        applyMaterialYouPreference.setVisible(sharedPreferences.getBoolean(SharedPreferencesUtils.ENABLE_MATERIAL_YOU, false));
        enableMaterialYouSwitchPreference.setOnPreferenceChangeListener((preference, newValue) -> {
            if ((Boolean) newValue) {
                MaterialYouUtils.changeTheme(activity, executor, new Handler(), redditDataRoomDatabase, customThemeWrapper, lightThemeSharedPreferences, darkThemeSharedPreferences, amoledThemeSharedPreferences, null);
                applyMaterialYouPreference.setVisible(true);
            } else {
                applyMaterialYouPreference.setVisible(false);
            }
            return true;
        });
        applyMaterialYouPreference.setOnPreferenceClickListener(preference -> {
            MaterialYouUtils.changeTheme(activity, executor, new Handler(), redditDataRoomDatabase, customThemeWrapper, lightThemeSharedPreferences, darkThemeSharedPreferences, amoledThemeSharedPreferences, null);
            return true;
        });
    }
    customThemeViewModel = new ViewModelProvider(this, new CustomThemeViewModel.Factory(redditDataRoomDatabase)).get(CustomThemeViewModel.class);
    customThemeViewModel.getCurrentLightThemeLiveData().observe(this, customTheme -> {
        if (customizeLightThemePreference != null) {
            if (customTheme != null) {
                customizeLightThemePreference.setVisible(true);
                customizeLightThemePreference.setSummary(customTheme.name);
            } else {
                customizeLightThemePreference.setVisible(false);
            }
        }
    });
    customThemeViewModel.getCurrentDarkThemeLiveData().observe(this, customTheme -> {
        if (customizeDarkThemePreference != null) {
            if (customTheme != null) {
                customizeDarkThemePreference.setVisible(true);
                customizeDarkThemePreference.setSummary(customTheme.name);
            } else {
                customizeDarkThemePreference.setVisible(false);
            }
        }
    });
    customThemeViewModel.getCurrentAmoledThemeLiveData().observe(this, customTheme -> {
        if (customizeAmoledThemePreference != null) {
            if (customTheme != null) {
                customizeAmoledThemePreference.setVisible(true);
                customizeAmoledThemePreference.setSummary(customTheme.name);
            } else {
                customizeAmoledThemePreference.setVisible(false);
            }
        }
    });
}
Also used : RecreateActivityEvent(ml.docilealligator.infinityforreddit.events.RecreateActivityEvent) SwitchPreference(androidx.preference.SwitchPreference) SwitchPreference(androidx.preference.SwitchPreference) Preference(androidx.preference.Preference) ListPreference(androidx.preference.ListPreference) Handler(android.os.Handler) Intent(android.content.Intent) CustomThemeViewModel(ml.docilealligator.infinityforreddit.customtheme.CustomThemeViewModel) ListPreference(androidx.preference.ListPreference) ViewModelProvider(androidx.lifecycle.ViewModelProvider)

Example 70 with ViewModelProvider

use of androidx.lifecycle.ViewModelProvider in project Infinity-For-Reddit by Docile-Alligator.

the class InboxFragment method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_inbox, container, false);
    ((Infinity) mActivity.getApplication()).getAppComponent().inject(this);
    ButterKnife.bind(this, rootView);
    EventBus.getDefault().register(this);
    applyTheme();
    Bundle arguments = getArguments();
    if (arguments == null) {
        return rootView;
    }
    mAccessToken = getArguments().getString(EXTRA_ACCESS_TOKEN);
    mGlide = Glide.with(this);
    if (mActivity.isImmersiveInterface()) {
        mRecyclerView.setPadding(0, 0, 0, mActivity.getNavBarHeight());
    }
    mWhere = arguments.getString(EXTRA_MESSAGE_WHERE, FetchMessage.WHERE_INBOX);
    mAdapter = new MessageRecyclerViewAdapter(mActivity, mOauthRetrofit, mCustomThemeWrapper, mAccessToken, mWhere, () -> mMessageViewModel.retryLoadingMore());
    mLinearLayoutManager = new LinearLayoutManagerBugFixed(mActivity);
    mRecyclerView.setLayoutManager(mLinearLayoutManager);
    mRecyclerView.setAdapter(mAdapter);
    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mActivity, mLinearLayoutManager.getOrientation());
    mRecyclerView.addItemDecoration(dividerItemDecoration);
    if (mActivity instanceof RecyclerViewContentScrollingInterface) {
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                if (dy > 0) {
                    ((RecyclerViewContentScrollingInterface) mActivity).contentScrollDown();
                } else if (dy < 0) {
                    ((RecyclerViewContentScrollingInterface) mActivity).contentScrollUp();
                }
            }
        });
    }
    MessageViewModel.Factory factory = new MessageViewModel.Factory(mOauthRetrofit, getResources().getConfiguration().locale, mAccessToken, mWhere);
    mMessageViewModel = new ViewModelProvider(this, factory).get(MessageViewModel.class);
    mMessageViewModel.getMessages().observe(getViewLifecycleOwner(), messages -> mAdapter.submitList(messages));
    mMessageViewModel.hasMessage().observe(getViewLifecycleOwner(), hasMessage -> {
        mSwipeRefreshLayout.setRefreshing(false);
        if (hasMessage) {
            mFetchMessageInfoLinearLayout.setVisibility(View.GONE);
        } else {
            mFetchMessageInfoLinearLayout.setOnClickListener(null);
            showErrorView(R.string.no_messages);
        }
    });
    mMessageViewModel.getInitialLoadingState().observe(getViewLifecycleOwner(), networkState -> {
        if (networkState.getStatus().equals(NetworkState.Status.SUCCESS)) {
            mSwipeRefreshLayout.setRefreshing(false);
        } else if (networkState.getStatus().equals(NetworkState.Status.FAILED)) {
            mSwipeRefreshLayout.setRefreshing(false);
            mFetchMessageInfoLinearLayout.setOnClickListener(view -> {
                mFetchMessageInfoLinearLayout.setVisibility(View.GONE);
                mMessageViewModel.refresh();
                mAdapter.setNetworkState(null);
            });
            showErrorView(R.string.load_messages_failed);
        } else {
            mSwipeRefreshLayout.setRefreshing(true);
        }
    });
    mMessageViewModel.getPaginationNetworkState().observe(getViewLifecycleOwner(), networkState -> {
        mAdapter.setNetworkState(networkState);
    });
    mSwipeRefreshLayout.setOnRefreshListener(this::onRefresh);
    return rootView;
}
Also used : DividerItemDecoration(androidx.recyclerview.widget.DividerItemDecoration) Context(android.content.Context) LinearLayout(android.widget.LinearLayout) Bundle(android.os.Bundle) ButterKnife(butterknife.ButterKnife) RecyclerViewContentScrollingInterface(ml.docilealligator.infinityforreddit.RecyclerViewContentScrollingInterface) NonNull(androidx.annotation.NonNull) R(ml.docilealligator.infinityforreddit.R) RepliedToPrivateMessageEvent(ml.docilealligator.infinityforreddit.events.RepliedToPrivateMessageEvent) ImageView(android.widget.ImageView) NetworkState(ml.docilealligator.infinityforreddit.NetworkState) FetchMessage(ml.docilealligator.infinityforreddit.message.FetchMessage) FragmentCommunicator(ml.docilealligator.infinityforreddit.FragmentCommunicator) Infinity(ml.docilealligator.infinityforreddit.Infinity) CustomThemeWrapper(ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper) BindView(butterknife.BindView) Inject(javax.inject.Inject) RequestManager(com.bumptech.glide.RequestManager) EventBus(org.greenrobot.eventbus.EventBus) BaseActivity(ml.docilealligator.infinityforreddit.activities.BaseActivity) Fragment(androidx.fragment.app.Fragment) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) Named(javax.inject.Named) RedditDataRoomDatabase(ml.docilealligator.infinityforreddit.RedditDataRoomDatabase) LinearLayoutManagerBugFixed(ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed) ViewModelProvider(androidx.lifecycle.ViewModelProvider) LayoutInflater(android.view.LayoutInflater) SwipeRefreshLayout(androidx.swiperefreshlayout.widget.SwipeRefreshLayout) ViewGroup(android.view.ViewGroup) Retrofit(retrofit2.Retrofit) MessageViewModel(ml.docilealligator.infinityforreddit.message.MessageViewModel) TextView(android.widget.TextView) Glide(com.bumptech.glide.Glide) Subscribe(org.greenrobot.eventbus.Subscribe) SharedPreferences(android.content.SharedPreferences) MessageRecyclerViewAdapter(ml.docilealligator.infinityforreddit.adapters.MessageRecyclerViewAdapter) LinearLayoutManagerBugFixed(ml.docilealligator.infinityforreddit.customviews.LinearLayoutManagerBugFixed) Bundle(android.os.Bundle) DividerItemDecoration(androidx.recyclerview.widget.DividerItemDecoration) ImageView(android.widget.ImageView) BindView(butterknife.BindView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) TextView(android.widget.TextView) RecyclerViewContentScrollingInterface(ml.docilealligator.infinityforreddit.RecyclerViewContentScrollingInterface) MessageViewModel(ml.docilealligator.infinityforreddit.message.MessageViewModel) RecyclerView(androidx.recyclerview.widget.RecyclerView) MessageRecyclerViewAdapter(ml.docilealligator.infinityforreddit.adapters.MessageRecyclerViewAdapter) ViewModelProvider(androidx.lifecycle.ViewModelProvider)

Aggregations

ViewModelProvider (androidx.lifecycle.ViewModelProvider)378 View (android.view.View)124 TextView (android.widget.TextView)77 Bundle (android.os.Bundle)73 RecyclerView (androidx.recyclerview.widget.RecyclerView)70 Intent (android.content.Intent)69 LinearLayoutManager (androidx.recyclerview.widget.LinearLayoutManager)57 NonNull (androidx.annotation.NonNull)53 Nullable (androidx.annotation.Nullable)45 List (java.util.List)38 ArrayList (java.util.ArrayList)33 ViewGroup (android.view.ViewGroup)30 Toolbar (androidx.appcompat.widget.Toolbar)28 MenuItem (android.view.MenuItem)27 Snackbar (com.google.android.material.snackbar.Snackbar)27 Uri (android.net.Uri)26 LayoutInflater (android.view.LayoutInflater)26 BottomSheetEvent (xyz.zedler.patrick.grocy.model.BottomSheetEvent)25 ImageView (android.widget.ImageView)24 Fragment (androidx.fragment.app.Fragment)24