Search in sources :

Example 1 with R

use of me.ccrama.redditslide.R in project Slide by ccrama.

the class SubmissionAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder2, final int pos) {
    int i = pos != 0 ? pos - 1 : pos;
    if (holder2 instanceof SubmissionViewHolder) {
        final SubmissionViewHolder holder = (SubmissionViewHolder) holder2;
        final Submission submission = dataSet.posts.get(i);
        CreateCardView.colorCard(submission.getSubredditName().toLowerCase(Locale.ENGLISH), holder.itemView, subreddit, (subreddit.equals("frontpage") || subreddit.equals("mod") || subreddit.equals("friends") || (subreddit.equals("all")) || subreddit.contains(".") || subreddit.contains("+")));
        holder.itemView.setOnClickListener(new OnSingleClickListener() {

            @Override
            public void onSingleClick(View v) {
                if (Authentication.didOnline || submission.getComments() != null) {
                    holder.title.setAlpha(0.54f);
                    holder.body.setAlpha(0.54f);
                    if (context instanceof MainActivity) {
                        final MainActivity a = (MainActivity) context;
                        if (a.singleMode && a.commentPager && a.adapter instanceof MainActivity.MainPagerAdapterComment) {
                            if (a.openingComments != submission) {
                                clicked = holder2.getBindingAdapterPosition();
                                a.openingComments = submission;
                                a.toOpenComments = a.pager.getCurrentItem() + 1;
                                a.currentComment = holder.getBindingAdapterPosition() - 1;
                                ((MainActivity.MainPagerAdapterComment) (a).adapter).storedFragment = (a).adapter.getCurrentFragment();
                                ((MainActivity.MainPagerAdapterComment) (a).adapter).size = a.toOpenComments + 1;
                                try {
                                    a.adapter.notifyDataSetChanged();
                                } catch (Exception ignored) {
                                }
                            }
                            a.pager.postDelayed(new Runnable() {

                                @Override
                                public void run() {
                                    a.pager.setCurrentItem(a.pager.getCurrentItem() + 1, true);
                                }
                            }, 400);
                        } else {
                            Intent i2 = new Intent(context, CommentsScreen.class);
                            i2.putExtra(CommentsScreen.EXTRA_PAGE, holder2.getBindingAdapterPosition() - 1);
                            i2.putExtra(CommentsScreen.EXTRA_SUBREDDIT, subreddit);
                            i2.putExtra("fullname", submission.getFullName());
                            context.startActivityForResult(i2, 940);
                            clicked = holder2.getBindingAdapterPosition();
                        }
                    } else if (context instanceof SubredditView) {
                        final SubredditView a = (SubredditView) context;
                        if (a.singleMode && a.commentPager) {
                            if (a.openingComments != submission) {
                                clicked = holder2.getBindingAdapterPosition();
                                a.openingComments = submission;
                                a.currentComment = holder.getBindingAdapterPosition() - 1;
                                ((SubredditView.SubredditPagerAdapterComment) (a).adapter).storedFragment = (a).adapter.getCurrentFragment();
                                ((SubredditView.SubredditPagerAdapterComment) a.adapter).size = 3;
                                a.adapter.notifyDataSetChanged();
                            }
                            a.pager.postDelayed(new Runnable() {

                                @Override
                                public void run() {
                                    a.pager.setCurrentItem(a.pager.getCurrentItem() + 1, true);
                                }
                            }, 400);
                        } else {
                            Intent i2 = new Intent(context, CommentsScreen.class);
                            i2.putExtra(CommentsScreen.EXTRA_PAGE, holder2.getBindingAdapterPosition() - 1);
                            i2.putExtra(CommentsScreen.EXTRA_SUBREDDIT, subreddit);
                            i2.putExtra("fullname", submission.getFullName());
                            context.startActivityForResult(i2, 940);
                            clicked = holder2.getBindingAdapterPosition();
                        }
                    }
                } else {
                    if (!Reddit.appRestart.contains("offlinepopup")) {
                        new AlertDialog.Builder(context).setTitle(R.string.cache_no_comments_found).setMessage(R.string.cache_no_comments_found_message).setCancelable(false).setPositiveButton(R.string.btn_ok, (dialog, which) -> Reddit.appRestart.edit().putString("offlinepopup", "").apply()).show();
                    } else {
                        Snackbar s = Snackbar.make(holder.itemView, R.string.cache_no_comments_found_snackbar, Snackbar.LENGTH_SHORT);
                        s.setAction(R.string.misc_more_info, new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                new AlertDialog.Builder(context).setTitle(R.string.cache_no_comments_found).setMessage(R.string.cache_no_comments_found_message).setCancelable(false).setPositiveButton(R.string.btn_ok, (dialog, which) -> Reddit.appRestart.edit().putString("offlinepopup", "").apply()).show();
                            }
                        });
                        LayoutUtils.showSnackbar(s);
                    }
                }
            }
        });
        new PopulateSubmissionViewHolder().populateSubmissionViewHolder(holder, submission, context, false, false, dataSet.posts, listView, custom, dataSet.offline, dataSet.subreddit.toLowerCase(Locale.ENGLISH), null);
    }
    if (holder2 instanceof SubmissionFooterViewHolder) {
        Handler handler = new Handler();
        final Runnable r = new Runnable() {

            public void run() {
                notifyItemChanged(dataSet.posts.size() + // the loading spinner to replaced by nomoreposts.xml
                1);
            }
        };
        handler.post(r);
        if (holder2.itemView.findViewById(R.id.reload) != null) {
            holder2.itemView.findViewById(R.id.reload).setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    ((SubmissionsView) displayer).forceRefresh();
                }
            });
        }
    }
    if (holder2 instanceof SpacerViewHolder) {
        View header = (context).findViewById(R.id.header);
        int height = header.getHeight();
        if (height == 0) {
            header.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            height = header.getMeasuredHeight();
            holder2.itemView.findViewById(R.id.height).setLayoutParams(new LinearLayout.LayoutParams(holder2.itemView.getWidth(), height));
            if (listView.getLayoutManager() instanceof CatchStaggeredGridLayoutManager) {
                CatchStaggeredGridLayoutManager.LayoutParams layoutParams = new CatchStaggeredGridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
                layoutParams.setFullSpan(true);
                holder2.itemView.setLayoutParams(layoutParams);
            }
        } else {
            holder2.itemView.findViewById(R.id.height).setLayoutParams(new LinearLayout.LayoutParams(holder2.itemView.getWidth(), height));
            if (listView.getLayoutManager() instanceof CatchStaggeredGridLayoutManager) {
                CatchStaggeredGridLayoutManager.LayoutParams layoutParams = new CatchStaggeredGridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
                layoutParams.setFullSpan(true);
                holder2.itemView.setLayoutParams(layoutParams);
            }
        }
    }
}
Also used : AlertDialog(androidx.appcompat.app.AlertDialog) LayoutUtils(me.ccrama.redditslide.util.LayoutUtils) LinearLayout(android.widget.LinearLayout) SettingValues(me.ccrama.redditslide.SettingValues) AlertDialog(androidx.appcompat.app.AlertDialog) R(me.ccrama.redditslide.R) Submission(net.dean.jraw.models.Submission) MainActivity(me.ccrama.redditslide.Activities.MainActivity) Intent(android.content.Intent) ArrayList(java.util.ArrayList) OnSingleClickListener(me.ccrama.redditslide.util.OnSingleClickListener) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) Locale(java.util.Locale) Handler(android.os.Handler) SubredditView(me.ccrama.redditslide.Activities.SubredditView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) CommentsScreen(me.ccrama.redditslide.Activities.CommentsScreen) LayoutInflater(android.view.LayoutInflater) Reddit(me.ccrama.redditslide.Reddit) Authentication(me.ccrama.redditslide.Authentication) ViewGroup(android.view.ViewGroup) PopulateSubmissionViewHolder(me.ccrama.redditslide.SubmissionViews.PopulateSubmissionViewHolder) CatchStaggeredGridLayoutManager(me.ccrama.redditslide.Views.CatchStaggeredGridLayoutManager) List(java.util.List) CreateCardView(me.ccrama.redditslide.Views.CreateCardView) Activity(android.app.Activity) Snackbar(com.google.android.material.snackbar.Snackbar) CatchStaggeredGridLayoutManager(me.ccrama.redditslide.Views.CatchStaggeredGridLayoutManager) OnSingleClickListener(me.ccrama.redditslide.util.OnSingleClickListener) SubredditView(me.ccrama.redditslide.Activities.SubredditView) MainActivity(me.ccrama.redditslide.Activities.MainActivity) PopulateSubmissionViewHolder(me.ccrama.redditslide.SubmissionViews.PopulateSubmissionViewHolder) CommentsScreen(me.ccrama.redditslide.Activities.CommentsScreen) Submission(net.dean.jraw.models.Submission) PopulateSubmissionViewHolder(me.ccrama.redditslide.SubmissionViews.PopulateSubmissionViewHolder) Handler(android.os.Handler) Intent(android.content.Intent) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) SubredditView(me.ccrama.redditslide.Activities.SubredditView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) CreateCardView(me.ccrama.redditslide.Views.CreateCardView) LinearLayout(android.widget.LinearLayout) Snackbar(com.google.android.material.snackbar.Snackbar)

Example 2 with R

use of me.ccrama.redditslide.R in project Slide by ccrama.

the class MainActivity method doSubOnlyStuff.

public void doSubOnlyStuff(final Subreddit subreddit) {
    findViewById(R.id.loader).setVisibility(View.GONE);
    if (subreddit.getSubredditType() != null) {
        canSubmit = !subreddit.getSubredditType().equals("RESTRICTED");
    } else {
        canSubmit = true;
    }
    if (subreddit.getSidebar() != null && !subreddit.getSidebar().isEmpty()) {
        findViewById(R.id.sidebar_text).setVisibility(View.VISIBLE);
        final String text = subreddit.getDataNode().get("description_html").asText().trim();
        setViews(text, subreddit.getDisplayName(), sidebarBody, sidebarOverflow);
        // get all subs that have Notifications enabled
        ArrayList<String> rawSubs = StringUtil.stringToArray(Reddit.appRestart.getString(CheckForMail.SUBS_TO_GET, ""));
        HashMap<String, Integer> subThresholds = new HashMap<>();
        for (String s : rawSubs) {
            try {
                String[] split = s.split(":");
                subThresholds.put(split[0].toLowerCase(Locale.ENGLISH), Integer.valueOf(split[1]));
            } catch (Exception ignored) {
            // do nothing
            }
        }
        // whether or not this subreddit was in the keySet
        boolean isNotified = subThresholds.containsKey(subreddit.getDisplayName().toLowerCase(Locale.ENGLISH));
        ((AppCompatCheckBox) findViewById(R.id.notify_posts_state)).setChecked(isNotified);
    } else {
        findViewById(R.id.sidebar_text).setVisibility(View.GONE);
    }
    {
        View collection = findViewById(R.id.collection);
        if (Authentication.isLoggedIn) {
            collection.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    new AsyncTask<Void, Void, Void>() {

                        HashMap<String, MultiReddit> multis = new HashMap<String, MultiReddit>();

                        @Override
                        protected Void doInBackground(Void... params) {
                            if (UserSubscriptions.multireddits == null) {
                                UserSubscriptions.syncMultiReddits(MainActivity.this);
                            }
                            for (MultiReddit r : UserSubscriptions.multireddits) {
                                multis.put(r.getDisplayName(), r);
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void aVoid) {
                            new MaterialDialog.Builder(MainActivity.this).title(getString(R.string.multi_add_to, subreddit.getDisplayName())).items(multis.keySet()).itemsCallback(new MaterialDialog.ListCallback() {

                                @Override
                                public void onSelection(MaterialDialog dialog, View itemView, final int which, CharSequence text) {
                                    new AsyncTask<Void, Void, Void>() {

                                        @Override
                                        protected Void doInBackground(Void... params) {
                                            try {
                                                final String multiName = multis.keySet().toArray(new String[0])[which];
                                                List<String> subs = new ArrayList<String>();
                                                for (MultiSubreddit sub : multis.get(multiName).getSubreddits()) {
                                                    subs.add(sub.getDisplayName());
                                                }
                                                subs.add(subreddit.getDisplayName());
                                                new MultiRedditManager(Authentication.reddit).createOrUpdate(new MultiRedditUpdateRequest.Builder(Authentication.name, multiName).subreddits(subs).build());
                                                UserSubscriptions.syncMultiReddits(MainActivity.this);
                                                runOnUiThread(new Runnable() {

                                                    @Override
                                                    public void run() {
                                                        drawerLayout.closeDrawers();
                                                        Snackbar s = Snackbar.make(mToolbar, getString(R.string.multi_subreddit_added, multiName), Snackbar.LENGTH_LONG);
                                                        LayoutUtils.showSnackbar(s);
                                                    }
                                                });
                                            } catch (final NetworkException | ApiException e) {
                                                runOnUiThread(new Runnable() {

                                                    @Override
                                                    public void run() {
                                                        runOnUiThread(new Runnable() {

                                                            @Override
                                                            public void run() {
                                                                Snackbar.make(mToolbar, getString(R.string.multi_error), Snackbar.LENGTH_LONG).setAction(R.string.btn_ok, null).show();
                                                            }
                                                        });
                                                    }
                                                });
                                                e.printStackTrace();
                                            }
                                            return null;
                                        }
                                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                }
                            }).show();
                        }
                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                }
            });
        } else {
            collection.setVisibility(View.GONE);
        }
    }
    {
        final AppCompatCheckBox notifyStateCheckBox = (AppCompatCheckBox) findViewById(R.id.notify_posts_state);
        assert notifyStateCheckBox != null;
        notifyStateCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    final String sub = subreddit.getDisplayName();
                    if (!sub.equalsIgnoreCase("all") && !sub.equalsIgnoreCase("frontpage") && !sub.equalsIgnoreCase("friends") && !sub.equalsIgnoreCase("mod") && !sub.contains("+") && !sub.contains(".") && !sub.contains("/m/")) {
                        new AlertDialog.Builder(MainActivity.this).setTitle(getString(R.string.sub_post_notifs_title, sub)).setMessage(R.string.sub_post_notifs_msg).setPositiveButton(R.string.btn_ok, (dialog, which) -> new MaterialDialog.Builder(MainActivity.this).title(R.string.sub_post_notifs_threshold).items(new String[] { "1", "5", "10", "20", "40", "50" }).alwaysCallSingleChoiceCallback().itemsCallbackSingleChoice(0, new MaterialDialog.ListCallbackSingleChoice() {

                            @Override
                            public boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                ArrayList<String> subs = StringUtil.stringToArray(Reddit.appRestart.getString(CheckForMail.SUBS_TO_GET, ""));
                                subs.add(sub + ":" + text);
                                Reddit.appRestart.edit().putString(CheckForMail.SUBS_TO_GET, StringUtil.arrayToString(subs)).commit();
                                return true;
                            }
                        }).cancelable(false).show()).setNegativeButton(R.string.btn_cancel, null).setNegativeButton(R.string.btn_cancel, (dialog, which) -> notifyStateCheckBox.setChecked(false)).setOnCancelListener(dialog -> notifyStateCheckBox.setChecked(false)).show();
                    } else {
                        notifyStateCheckBox.setChecked(false);
                        Toast.makeText(MainActivity.this, R.string.sub_post_notifs_err, Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Intent cancelIntent = new Intent(MainActivity.this, CancelSubNotifs.class);
                    cancelIntent.putExtra(CancelSubNotifs.EXTRA_SUB, subreddit.getDisplayName());
                    startActivity(cancelIntent);
                }
            }
        });
    }
    {
        final TextView subscribe = (TextView) findViewById(R.id.subscribe);
        currentlySubbed = (!Authentication.isLoggedIn && usedArray.contains(subreddit.getDisplayName().toLowerCase(Locale.ENGLISH))) || subreddit.isUserSubscriber();
        MiscUtil.doSubscribeButtonText(currentlySubbed, subscribe);
        assert subscribe != null;
        subscribe.setOnClickListener(new View.OnClickListener() {

            private void doSubscribe() {
                if (Authentication.isLoggedIn) {
                    new AlertDialog.Builder(MainActivity.this).setTitle(getString(R.string.subscribe_to, subreddit.getDisplayName())).setPositiveButton(R.string.reorder_add_subscribe, (dialog, which) -> new AsyncTask<Void, Void, Boolean>() {

                        @Override
                        public void onPostExecute(Boolean success) {
                            if (!success) {
                                // If subreddit was removed from account or not
                                new AlertDialog.Builder(MainActivity.this).setTitle(R.string.force_change_subscription).setMessage(R.string.force_change_subscription_desc).setPositiveButton(R.string.btn_yes, (dialog1, which1) -> {
                                    // Force add the subscription
                                    changeSubscription(subreddit, true);
                                    Snackbar s = Snackbar.make(mToolbar, getString(R.string.misc_subscribed), Snackbar.LENGTH_LONG);
                                    LayoutUtils.showSnackbar(s);
                                }).setNegativeButton(R.string.btn_no, null).setCancelable(false).show();
                            } else {
                                changeSubscription(subreddit, true);
                            }
                        }

                        @Override
                        protected Boolean doInBackground(Void... params) {
                            try {
                                new AccountManager(Authentication.reddit).subscribe(subreddit);
                            } catch (NetworkException e) {
                                // Either network crashed or trying to unsubscribe to a subreddit that the account isn't subscribed to
                                return false;
                            }
                            return true;
                        }
                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)).setNeutralButton(R.string.btn_add_to_sublist, (dialog, which) -> {
                        // Force add the subscription
                        changeSubscription(subreddit, true);
                        Snackbar s = Snackbar.make(mToolbar, R.string.sub_added, Snackbar.LENGTH_LONG);
                        LayoutUtils.showSnackbar(s);
                    }).setNegativeButton(R.string.btn_cancel, null).show();
                } else {
                    changeSubscription(subreddit, true);
                }
            }

            private void doUnsubscribe() {
                if (Authentication.didOnline) {
                    new AlertDialog.Builder(MainActivity.this).setTitle(getString(R.string.unsubscribe_from, subreddit.getDisplayName())).setPositiveButton(R.string.reorder_remove_unsubscribe, (dialog, which) -> new AsyncTask<Void, Void, Boolean>() {

                        @Override
                        public void onPostExecute(Boolean success) {
                            if (!success) {
                                // If subreddit was removed from account or not
                                new AlertDialog.Builder(MainActivity.this).setTitle(R.string.force_change_subscription).setMessage(R.string.force_change_subscription_desc).setPositiveButton(R.string.btn_yes, (dialog12, which12) -> {
                                    // Force add the subscription
                                    changeSubscription(subreddit, false);
                                    Snackbar s = Snackbar.make(mToolbar, getString(R.string.misc_unsubscribed), Snackbar.LENGTH_LONG);
                                    LayoutUtils.showSnackbar(s);
                                }).setNegativeButton(R.string.btn_no, null).setCancelable(false).show();
                            } else {
                                changeSubscription(subreddit, false);
                            }
                        }

                        @Override
                        protected Boolean doInBackground(Void... params) {
                            try {
                                new AccountManager(Authentication.reddit).unsubscribe(subreddit);
                            } catch (NetworkException e) {
                                // Either network crashed or trying to unsubscribe to a subreddit that the account isn't subscribed to
                                return false;
                            }
                            return true;
                        }
                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)).setNeutralButton(R.string.just_unsub, (dialog, which) -> {
                        // Force add the subscription
                        changeSubscription(subreddit, false);
                        Snackbar s = Snackbar.make(mToolbar, R.string.misc_unsubscribed, Snackbar.LENGTH_LONG);
                        LayoutUtils.showSnackbar(s);
                    }).setNegativeButton(R.string.btn_cancel, null).show();
                } else {
                    changeSubscription(subreddit, false);
                }
            }

            @Override
            public void onClick(View v) {
                if (!currentlySubbed) {
                    doSubscribe();
                } else {
                    doUnsubscribe();
                }
                MiscUtil.doSubscribeButtonText(currentlySubbed, subscribe);
            }
        });
    }
    if (!subreddit.getPublicDescription().isEmpty()) {
        findViewById(R.id.sub_title).setVisibility(View.VISIBLE);
        setViews(subreddit.getDataNode().get("public_description_html").asText(), subreddit.getDisplayName().toLowerCase(Locale.ENGLISH), ((SpoilerRobotoTextView) findViewById(R.id.sub_title)), (CommentOverflow) findViewById(R.id.sub_title_overflow));
    } else {
        findViewById(R.id.sub_title).setVisibility(View.GONE);
    }
    ((ImageView) findViewById(R.id.subimage)).setImageResource(0);
    if (subreddit.getDataNode().has("icon_img") && !subreddit.getDataNode().get("icon_img").asText().isEmpty()) {
        findViewById(R.id.subimage).setVisibility(View.VISIBLE);
        ((Reddit) getApplication()).getImageLoader().displayImage(subreddit.getDataNode().get("icon_img").asText(), (ImageView) findViewById(R.id.subimage));
    } else {
        findViewById(R.id.subimage).setVisibility(View.GONE);
    }
    String bannerImage = subreddit.getBannerImage();
    if (bannerImage != null && !bannerImage.isEmpty()) {
        findViewById(R.id.sub_banner).setVisibility(View.VISIBLE);
        ((Reddit) getApplication()).getImageLoader().displayImage(bannerImage, (ImageView) findViewById(R.id.sub_banner));
    } else {
        findViewById(R.id.sub_banner).setVisibility(View.GONE);
    }
    ((TextView) findViewById(R.id.subscribers)).setText(getString(R.string.subreddit_subscribers_string, subreddit.getLocalizedSubscriberCount()));
    findViewById(R.id.subscribers).setVisibility(View.VISIBLE);
    ((TextView) findViewById(R.id.active_users)).setText(getString(R.string.subreddit_active_users_string_new, subreddit.getLocalizedAccountsActive()));
    findViewById(R.id.active_users).setVisibility(View.VISIBLE);
}
Also used : AlertDialog(androidx.appcompat.app.AlertDialog) Arrays(java.util.Arrays) Bundle(android.os.Bundle) R(me.ccrama.redditslide.R) NonNull(androidx.annotation.NonNull) AnimatorUtil(me.ccrama.redditslide.util.AnimatorUtil) Uri(android.net.Uri) ImageView(android.widget.ImageView) PostMatch(me.ccrama.redditslide.PostMatch) ColorDrawable(android.graphics.drawable.ColorDrawable) ContentType(me.ccrama.redditslide.ContentType) AppCompatCheckBox(androidx.appcompat.widget.AppCompatCheckBox) UserRecordPaginator(net.dean.jraw.paginators.UserRecordPaginator) NeverAgainWhenClickedOnce(org.ligi.snackengage.conditions.NeverAgainWhenClickedOnce) OnSingleClickListener(me.ccrama.redditslide.util.OnSingleClickListener) ShortcutManagerCompat(androidx.core.content.pm.ShortcutManagerCompat) HorizontalScrollView(android.widget.HorizontalScrollView) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) Manifest(android.Manifest) Handler(android.os.Handler) Map(java.util.Map) Fragment(androidx.fragment.app.Fragment) ClipboardManager(android.content.ClipboardManager) Canvas(android.graphics.Canvas) JsonNode(com.fasterxml.jackson.databind.JsonNode) ContextCompat(androidx.core.content.ContextCompat) ProUtil(me.ccrama.redditslide.util.ProUtil) Log(android.util.Log) CardView(androidx.cardview.widget.CardView) WithLimitedNumberOfTimes(org.ligi.snackengage.conditions.WithLimitedNumberOfTimes) SubredditPosts(me.ccrama.redditslide.Adapters.SubredditPosts) CheckForMail(me.ccrama.redditslide.Notifications.CheckForMail) KeyboardUtil(me.ccrama.redditslide.util.KeyboardUtil) IntentFilter(android.content.IntentFilter) CommentPage(me.ccrama.redditslide.Fragments.CommentPage) SidebarLayout(me.ccrama.redditslide.Views.SidebarLayout) Set(java.util.Set) DensityUtils(me.ccrama.redditslide.ForceTouch.util.DensityUtils) NotificationJobScheduler(me.ccrama.redditslide.Notifications.NotificationJobScheduler) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) Palette(me.ccrama.redditslide.Visuals.Palette) SimpleTextWatcher(me.ccrama.redditslide.util.stubs.SimpleTextWatcher) SubredditPaginator(net.dean.jraw.paginators.SubredditPaginator) Executors(java.util.concurrent.Executors) CatchStaggeredGridLayoutManager(me.ccrama.redditslide.Views.CatchStaggeredGridLayoutManager) SortingUtil(me.ccrama.redditslide.util.SortingUtil) KVManger(com.lusfold.androidkeyvaluestore.core.KVManger) DrawerItemsDialog(me.ccrama.redditslide.Fragments.DrawerItemsDialog) DrawableUtil(me.ccrama.redditslide.util.DrawableUtil) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) BuildConfig(me.ccrama.redditslide.BuildConfig) SubmissionParser(me.ccrama.redditslide.util.SubmissionParser) AfterNumberOfOpportunities(org.ligi.snackengage.conditions.AfterNumberOfOpportunities) ViewDragHelper(androidx.customview.widget.ViewDragHelper) DrawerLayout(androidx.drawerlayout.widget.DrawerLayout) BaseSnack(org.ligi.snackengage.snacks.BaseSnack) HasSeen(me.ccrama.redditslide.HasSeen) ViewPager(androidx.viewpager.widget.ViewPager) Dialog(android.app.Dialog) Editable(android.text.Editable) AccountManager(net.dean.jraw.managers.AccountManager) ArrayList(java.util.ArrayList) MiscUtil(me.ccrama.redditslide.util.MiscUtil) MenuInflater(android.view.MenuInflater) Toast(android.widget.Toast) Menu(android.view.Menu) UserSubscriptions(me.ccrama.redditslide.UserSubscriptions) OpenRedditLink(me.ccrama.redditslide.OpenRedditLink) MultiRedditUpdateRequest(net.dean.jraw.http.MultiRedditUpdateRequest) TimePeriod(net.dean.jraw.paginators.TimePeriod) SettingsThemeFragment(me.ccrama.redditslide.ui.settings.SettingsThemeFragment) StringUtil(me.ccrama.redditslide.util.StringUtil) FragmentManager(androidx.fragment.app.FragmentManager) SettingsSubAdapter(me.ccrama.redditslide.ui.settings.SettingsSubAdapter) Parcelable(android.os.Parcelable) FlairTemplate(net.dean.jraw.models.FlairTemplate) UserSubscriptions.modOf(me.ccrama.redditslide.UserSubscriptions.modOf) Reddit(me.ccrama.redditslide.Reddit) ColorPreferences(me.ccrama.redditslide.Visuals.ColorPreferences) Field(java.lang.reflect.Field) AutoCompleteTextView(android.widget.AutoCompleteTextView) MultiRedditManager(net.dean.jraw.managers.MultiRedditManager) ContextThemeWrapper(androidx.appcompat.view.ContextThemeWrapper) Gravity(android.view.Gravity) MySynccitUpdateTask(me.ccrama.redditslide.Synccit.MySynccitUpdateTask) SharedPreferences(android.content.SharedPreferences) IconCompat(androidx.core.graphics.drawable.IconCompat) Configuration(android.content.res.Configuration) EditText(android.widget.EditText) ValueAnimator(android.animation.ValueAnimator) LinearLayout(android.widget.LinearLayout) ToggleSwipeViewPager(me.ccrama.redditslide.Views.ToggleSwipeViewPager) MultiSubreddit(net.dean.jraw.models.MultiSubreddit) CommentCacheAsync(me.ccrama.redditslide.CommentCacheAsync) SideArrayAdapter(me.ccrama.redditslide.Adapters.SideArrayAdapter) PackageManager(android.content.pm.PackageManager) TimeUtils(me.ccrama.redditslide.util.TimeUtils) EditTextValidator(me.ccrama.redditslide.util.EditTextValidator) Spannable(android.text.Spannable) WindowManager(android.view.WindowManager) SettingsGeneralFragment(me.ccrama.redditslide.ui.settings.SettingsGeneralFragment) Animator(android.animation.Animator) DrawableRes(androidx.annotation.DrawableRes) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) AccelerateDecelerateInterpolator(android.view.animation.AccelerateDecelerateInterpolator) ActionBarDrawerToggle(androidx.appcompat.app.ActionBarDrawerToggle) Locale(java.util.Locale) View(android.view.View) Sorting(net.dean.jraw.paginators.Sorting) SynccitRead(me.ccrama.redditslide.Synccit.SynccitRead) ArgbEvaluator(android.animation.ArgbEvaluator) FragmentStatePagerAdapter(androidx.fragment.app.FragmentStatePagerAdapter) AutoCacheScheduler(me.ccrama.redditslide.Autocache.AutoCacheScheduler) CaseInsensitiveArrayList(me.ccrama.redditslide.CaseInsensitiveArrayList) NetworkStateReceiver(me.ccrama.redditslide.util.NetworkStateReceiver) NotificationManager(android.app.NotificationManager) AsyncTask(android.os.AsyncTask) TabLayout(com.google.android.material.tabs.TabLayout) Authentication(me.ccrama.redditslide.Authentication) ApiException(net.dean.jraw.ApiException) ViewGroup(android.view.ViewGroup) List(java.util.List) NetworkUtil(me.ccrama.redditslide.util.NetworkUtil) TextView(android.widget.TextView) LinearInterpolator(android.view.animation.LinearInterpolator) RelativeLayout(android.widget.RelativeLayout) Toolbar(androidx.appcompat.widget.Toolbar) ListView(android.widget.ListView) CommentOverflow(me.ccrama.redditslide.Views.CommentOverflow) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Window(android.view.Window) EditorInfo(android.view.inputmethod.EditorInfo) Snackbar(com.google.android.material.snackbar.Snackbar) RequestPermission(androidx.activity.result.contract.ActivityResultContracts.RequestPermission) LayoutUtils(me.ccrama.redditslide.util.LayoutUtils) Context(android.content.Context) SettingValues(me.ccrama.redditslide.SettingValues) KeyEvent(android.view.KeyEvent) AlertDialog(androidx.appcompat.app.AlertDialog) ResourcesCompat(androidx.core.content.res.ResourcesCompat) ModerationManager(net.dean.jraw.managers.ModerationManager) Submission(net.dean.jraw.models.Submission) Pair(android.util.Pair) Intent(android.content.Intent) HashMap(java.util.HashMap) Constants(me.ccrama.redditslide.Constants) PreCachingLayoutManager(me.ccrama.redditslide.Views.PreCachingLayoutManager) LogUtil(me.ccrama.redditslide.util.LogUtil) MenuItem(android.view.MenuItem) InputMethodManager(android.view.inputmethod.InputMethodManager) ClipData(android.content.ClipData) HashSet(java.util.HashSet) UserRecord(net.dean.jraw.models.UserRecord) ManageOfflineContent(me.ccrama.redditslide.ui.settings.ManageOfflineContent) Build(android.os.Build) ShortcutInfoCompat(androidx.core.content.pm.ShortcutInfoCompat) ExecutorService(java.util.concurrent.ExecutorService) DialogInterface(android.content.DialogInterface) RateSnack(org.ligi.snackengage.snacks.RateSnack) ViewStub(android.view.ViewStub) MultiReddit(net.dean.jraw.models.MultiReddit) SwitchCompat(androidx.appcompat.widget.SwitchCompat) CompoundButton(android.widget.CompoundButton) ActivityResultLauncher(androidx.activity.result.ActivityResultLauncher) LayoutInflater(android.view.LayoutInflater) ImageFlairs(me.ccrama.redditslide.ImageFlairs) GravityCompat(androidx.core.view.GravityCompat) KVStore(com.lusfold.androidkeyvaluestore.KVStore) Point(android.graphics.Point) DialogAction(com.afollestad.materialdialogs.DialogAction) SnackEngage(org.ligi.snackengage.SnackEngage) ResolveInfo(android.content.pm.ResolveInfo) PopupMenu(androidx.appcompat.widget.PopupMenu) ImageUtil(me.ccrama.redditslide.util.ImageUtil) SettingsActivity(me.ccrama.redditslide.ui.settings.SettingsActivity) Bitmap(android.graphics.Bitmap) ViewTreeObserver(android.view.ViewTreeObserver) Subreddit(net.dean.jraw.models.Subreddit) Activity(android.app.Activity) NetworkException(net.dean.jraw.http.NetworkException) Collections(java.util.Collections) LoggedInAccount(net.dean.jraw.models.LoggedInAccount) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CaseInsensitiveArrayList(me.ccrama.redditslide.CaseInsensitiveArrayList) MultiSubreddit(net.dean.jraw.models.MultiSubreddit) MultiReddit(net.dean.jraw.models.MultiReddit) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) MultiRedditUpdateRequest(net.dean.jraw.http.MultiRedditUpdateRequest) AutoCompleteTextView(android.widget.AutoCompleteTextView) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) TextView(android.widget.TextView) ImageView(android.widget.ImageView) NetworkException(net.dean.jraw.http.NetworkException) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) AsyncTask(android.os.AsyncTask) Intent(android.content.Intent) ImageView(android.widget.ImageView) HorizontalScrollView(android.widget.HorizontalScrollView) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) CardView(androidx.cardview.widget.CardView) AutoCompleteTextView(android.widget.AutoCompleteTextView) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) View(android.view.View) TextView(android.widget.TextView) ListView(android.widget.ListView) ApiException(net.dean.jraw.ApiException) NetworkException(net.dean.jraw.http.NetworkException) Point(android.graphics.Point) AppCompatCheckBox(androidx.appcompat.widget.AppCompatCheckBox) MultiRedditManager(net.dean.jraw.managers.MultiRedditManager) AccountManager(net.dean.jraw.managers.AccountManager) CompoundButton(android.widget.CompoundButton) Snackbar(com.google.android.material.snackbar.Snackbar) ApiException(net.dean.jraw.ApiException)

Example 3 with R

use of me.ccrama.redditslide.R in project Slide by ccrama.

the class SubredditView method doSubOnlyStuff.

private void doSubOnlyStuff(final Subreddit subreddit) {
    if (!isFinishing()) {
        findViewById(R.id.loader).setVisibility(View.GONE);
        if (subreddit.getDataNode().has("subreddit_type") && !subreddit.getDataNode().get("subreddit_type").isNull()) {
            canSubmit = !subreddit.getDataNode().get("subreddit_type").asText().equalsIgnoreCase("RESTRICTED");
        }
        if (subreddit.getSidebar() != null && !subreddit.getSidebar().isEmpty()) {
            findViewById(R.id.sidebar_text).setVisibility(View.VISIBLE);
            final String text = subreddit.getDataNode().get("description_html").asText().trim();
            final SpoilerRobotoTextView body = (SpoilerRobotoTextView) findViewById(R.id.sidebar_text);
            CommentOverflow overflow = (CommentOverflow) findViewById(R.id.commentOverflow);
            setViews(text, subreddit.getDisplayName(), body, overflow);
            // get all subs that have Notifications enabled
            ArrayList<String> rawSubs = StringUtil.stringToArray(Reddit.appRestart.getString(CheckForMail.SUBS_TO_GET, ""));
            HashMap<String, Integer> subThresholds = new HashMap<>();
            for (String s : rawSubs) {
                try {
                    String[] split = s.split(":");
                    subThresholds.put(split[0].toLowerCase(Locale.ENGLISH), Integer.valueOf(split[1]));
                } catch (Exception ignored) {
                // do nothing
                }
            }
            // whether or not this subreddit was in the keySet
            boolean isNotified = subThresholds.containsKey(subreddit.getDisplayName().toLowerCase(Locale.ENGLISH));
            ((AppCompatCheckBox) findViewById(R.id.notify_posts_state)).setChecked(isNotified);
        } else {
            findViewById(R.id.sidebar_text).setVisibility(View.GONE);
        }
        View collection = findViewById(R.id.collection);
        if (Authentication.isLoggedIn) {
            collection.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    new AsyncTask<Void, Void, Void>() {

                        HashMap<String, MultiReddit> multis = new HashMap<String, MultiReddit>();

                        @Override
                        protected Void doInBackground(Void... params) {
                            if (UserSubscriptions.multireddits == null) {
                                UserSubscriptions.syncMultiReddits(SubredditView.this);
                            }
                            for (MultiReddit r : UserSubscriptions.multireddits) {
                                multis.put(r.getDisplayName(), r);
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void aVoid) {
                            new MaterialDialog.Builder(SubredditView.this).title("Add /r/" + subreddit.getDisplayName() + " to").items(multis.keySet()).itemsCallback(new MaterialDialog.ListCallback() {

                                @Override
                                public void onSelection(MaterialDialog dialog, View itemView, final int which, CharSequence text) {
                                    new AsyncTask<Void, Void, Void>() {

                                        @Override
                                        protected Void doInBackground(Void... params) {
                                            try {
                                                final String multiName = multis.keySet().toArray(new String[0])[which];
                                                List<String> subs = new ArrayList<String>();
                                                for (MultiSubreddit sub : multis.get(multiName).getSubreddits()) {
                                                    subs.add(sub.getDisplayName());
                                                }
                                                subs.add(subreddit.getDisplayName());
                                                new MultiRedditManager(Authentication.reddit).createOrUpdate(new MultiRedditUpdateRequest.Builder(Authentication.name, multiName).subreddits(subs).build());
                                                UserSubscriptions.syncMultiReddits(SubredditView.this);
                                                runOnUiThread(new Runnable() {

                                                    @Override
                                                    public void run() {
                                                        drawerLayout.closeDrawers();
                                                        Snackbar s = Snackbar.make(mToolbar, getString(R.string.multi_subreddit_added, multiName), Snackbar.LENGTH_LONG);
                                                        LayoutUtils.showSnackbar(s);
                                                    }
                                                });
                                            } catch (final NetworkException | ApiException e) {
                                                runOnUiThread(new Runnable() {

                                                    @Override
                                                    public void run() {
                                                        runOnUiThread(new Runnable() {

                                                            @Override
                                                            public void run() {
                                                                Snackbar.make(mToolbar, getString(R.string.multi_error), Snackbar.LENGTH_LONG).setAction(R.string.btn_ok, null).show();
                                                            }
                                                        });
                                                    }
                                                });
                                                e.printStackTrace();
                                            }
                                            return null;
                                        }
                                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                }
                            }).show();
                        }
                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                }
            });
        } else {
            collection.setVisibility(View.GONE);
        }
        {
            final TextView subscribe = (TextView) findViewById(R.id.subscribe);
            currentlySubbed = Authentication.isLoggedIn ? subreddit.isUserSubscriber() : UserSubscriptions.getSubscriptions(this).contains(subreddit.getDisplayName().toLowerCase(Locale.ENGLISH));
            MiscUtil.doSubscribeButtonText(currentlySubbed, subscribe);
            assert subscribe != null;
            subscribe.setOnClickListener(new View.OnClickListener() {

                private void doSubscribe() {
                    if (Authentication.isLoggedIn) {
                        new AlertDialog.Builder(SubredditView.this).setTitle(getString(R.string.subscribe_to, subreddit.getDisplayName())).setPositiveButton(R.string.reorder_add_subscribe, (dialog, which) -> new AsyncTask<Void, Void, Boolean>() {

                            @Override
                            public void onPostExecute(Boolean success) {
                                if (!success) {
                                    // If subreddit was removed from account or not
                                    new AlertDialog.Builder(SubredditView.this).setTitle(R.string.force_change_subscription).setMessage(R.string.force_change_subscription_desc).setPositiveButton(R.string.btn_yes, (dialog1, which1) -> {
                                        // Force add the subscription
                                        changeSubscription(subreddit, true);
                                        Snackbar s = Snackbar.make(mToolbar, getString(R.string.misc_subscribed), Snackbar.LENGTH_SHORT);
                                        LayoutUtils.showSnackbar(s);
                                    }).setNegativeButton(R.string.btn_no, null).setCancelable(false).show();
                                } else {
                                    changeSubscription(subreddit, true);
                                }
                            }

                            @Override
                            protected Boolean doInBackground(Void... params) {
                                try {
                                    new AccountManager(Authentication.reddit).subscribe(subreddit);
                                } catch (NetworkException e) {
                                    // Either network crashed or trying to unsubscribe to a subreddit that the account isn't subscribed to
                                    return false;
                                }
                                return true;
                            }
                        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)).setNegativeButton(R.string.btn_cancel, null).setNeutralButton(R.string.btn_add_to_sublist, (dialog, which) -> {
                            // Force add the subscription
                            changeSubscription(subreddit, true);
                            Snackbar s = Snackbar.make(mToolbar, R.string.sub_added, Snackbar.LENGTH_SHORT);
                            LayoutUtils.showSnackbar(s);
                        }).show();
                    } else {
                        changeSubscription(subreddit, true);
                    }
                }

                @Override
                public void onClick(View v) {
                    if (!currentlySubbed) {
                        doSubscribe();
                    } else {
                        doUnsubscribe();
                    }
                    MiscUtil.doSubscribeButtonText(currentlySubbed, subscribe);
                }

                private void doUnsubscribe() {
                    if (Authentication.didOnline) {
                        new AlertDialog.Builder(SubredditView.this).setTitle(getString(R.string.unsubscribe_from, subreddit.getDisplayName())).setPositiveButton(R.string.reorder_remove_unsubscribe, (dialog, which) -> new AsyncTask<Void, Void, Boolean>() {

                            @Override
                            public void onPostExecute(Boolean success) {
                                if (!success) {
                                    // If subreddit was removed from account or not
                                    new AlertDialog.Builder(SubredditView.this).setTitle(R.string.force_change_subscription).setMessage(R.string.force_change_subscription_desc).setPositiveButton(R.string.btn_yes, (dialog12, which12) -> {
                                        // Force add the subscription
                                        changeSubscription(subreddit, false);
                                        Snackbar s = Snackbar.make(mToolbar, getString(R.string.misc_unsubscribed), Snackbar.LENGTH_SHORT);
                                        LayoutUtils.showSnackbar(s);
                                    }).setNegativeButton(R.string.btn_no, null).setCancelable(false).show();
                                } else {
                                    changeSubscription(subreddit, false);
                                }
                            }

                            @Override
                            protected Boolean doInBackground(Void... params) {
                                try {
                                    new AccountManager(Authentication.reddit).unsubscribe(subreddit);
                                } catch (NetworkException e) {
                                    // Either network crashed or trying to unsubscribe to a subreddit that the account isn't subscribed to
                                    return false;
                                }
                                return true;
                            }
                        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)).setNeutralButton(R.string.just_unsub, (dialog, which) -> {
                            // Force add the subscription
                            changeSubscription(subreddit, false);
                            Snackbar s = Snackbar.make(mToolbar, R.string.misc_unsubscribed, Snackbar.LENGTH_SHORT);
                            LayoutUtils.showSnackbar(s);
                        }).setNegativeButton(R.string.btn_cancel, null).show();
                    } else {
                        changeSubscription(subreddit, false);
                    }
                }
            });
        }
        {
            final AppCompatCheckBox notifyStateCheckBox = (AppCompatCheckBox) findViewById(R.id.notify_posts_state);
            assert notifyStateCheckBox != null;
            notifyStateCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        final String sub = subreddit.getDisplayName();
                        if (!sub.equalsIgnoreCase("all") && !sub.equalsIgnoreCase("frontpage") && !sub.equalsIgnoreCase("friends") && !sub.equalsIgnoreCase("mod") && !sub.contains("+") && !sub.contains(".") && !sub.contains("/m/")) {
                            new AlertDialog.Builder(SubredditView.this).setTitle(getString(R.string.sub_post_notifs_title, sub)).setMessage(R.string.sub_post_notifs_msg).setPositiveButton(R.string.btn_ok, (dialog, which) -> new MaterialDialog.Builder(SubredditView.this).title(R.string.sub_post_notifs_threshold).items(new String[] { "1", "5", "10", "20", "40", "50" }).alwaysCallSingleChoiceCallback().itemsCallbackSingleChoice(0, new MaterialDialog.ListCallbackSingleChoice() {

                                @Override
                                public boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                    ArrayList<String> subs = StringUtil.stringToArray(Reddit.appRestart.getString(CheckForMail.SUBS_TO_GET, ""));
                                    subs.add(sub + ":" + text);
                                    Reddit.appRestart.edit().putString(CheckForMail.SUBS_TO_GET, StringUtil.arrayToString(subs)).commit();
                                    return true;
                                }
                            }).cancelable(false).show()).setNegativeButton(R.string.btn_cancel, null).setNegativeButton(R.string.btn_cancel, (dialog, which) -> notifyStateCheckBox.setChecked(false)).setOnCancelListener(dialog -> notifyStateCheckBox.setChecked(false)).show();
                        } else {
                            notifyStateCheckBox.setChecked(false);
                            Toast.makeText(SubredditView.this, R.string.sub_post_notifs_err, Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Intent cancelIntent = new Intent(SubredditView.this, CancelSubNotifs.class);
                        cancelIntent.putExtra(CancelSubNotifs.EXTRA_SUB, subreddit.getDisplayName());
                        startActivity(cancelIntent);
                    }
                }
            });
        }
        if (!subreddit.getPublicDescription().isEmpty()) {
            findViewById(R.id.sub_title).setVisibility(View.VISIBLE);
            setViews(subreddit.getDataNode().get("public_description_html").asText(), subreddit.getDisplayName().toLowerCase(Locale.ENGLISH), ((SpoilerRobotoTextView) findViewById(R.id.sub_title)), (CommentOverflow) findViewById(R.id.sub_title_overflow));
        } else {
            findViewById(R.id.sub_title).setVisibility(View.GONE);
        }
        if (subreddit.getDataNode().has("icon_img") && !subreddit.getDataNode().get("icon_img").asText().isEmpty()) {
            ((Reddit) getApplication()).getImageLoader().displayImage(subreddit.getDataNode().get("icon_img").asText(), (ImageView) findViewById(R.id.subimage));
        } else {
            findViewById(R.id.subimage).setVisibility(View.GONE);
        }
        String bannerImage = subreddit.getBannerImage();
        if (bannerImage != null && !bannerImage.isEmpty()) {
            findViewById(R.id.sub_banner).setVisibility(View.VISIBLE);
            ((Reddit) getApplication()).getImageLoader().displayImage(bannerImage, (ImageView) findViewById(R.id.sub_banner));
        } else {
            findViewById(R.id.sub_banner).setVisibility(View.GONE);
        }
        ((TextView) findViewById(R.id.subscribers)).setText(getString(R.string.subreddit_subscribers_string, subreddit.getLocalizedSubscriberCount()));
        findViewById(R.id.subscribers).setVisibility(View.VISIBLE);
        ((TextView) findViewById(R.id.active_users)).setText(getString(R.string.subreddit_active_users_string_new, subreddit.getLocalizedAccountsActive()));
        findViewById(R.id.active_users).setVisibility(View.VISIBLE);
    }
}
Also used : AlertDialog(androidx.appcompat.app.AlertDialog) ToggleSwipeViewPager(me.ccrama.redditslide.Views.ToggleSwipeViewPager) Bundle(android.os.Bundle) MultiSubreddit(net.dean.jraw.models.MultiSubreddit) R(me.ccrama.redditslide.R) NonNull(androidx.annotation.NonNull) Spannable(android.text.Spannable) ImageView(android.widget.ImageView) PostMatch(me.ccrama.redditslide.PostMatch) ColorDrawable(android.graphics.drawable.ColorDrawable) AppCompatCheckBox(androidx.appcompat.widget.AppCompatCheckBox) UserRecordPaginator(net.dean.jraw.paginators.UserRecordPaginator) BlankFragment(me.ccrama.redditslide.Fragments.BlankFragment) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) OnSingleClickListener(me.ccrama.redditslide.util.OnSingleClickListener) HorizontalScrollView(android.widget.HorizontalScrollView) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) Locale(java.util.Locale) Fragment(androidx.fragment.app.Fragment) View(android.view.View) Sorting(net.dean.jraw.paginators.Sorting) FragmentStatePagerAdapter(androidx.fragment.app.FragmentStatePagerAdapter) JsonNode(com.fasterxml.jackson.databind.JsonNode) ProUtil(me.ccrama.redditslide.util.ProUtil) Log(android.util.Log) CheckForMail(me.ccrama.redditslide.Notifications.CheckForMail) CoordinatorLayout(androidx.coordinatorlayout.widget.CoordinatorLayout) AsyncTask(android.os.AsyncTask) Authentication(me.ccrama.redditslide.Authentication) CommentPage(me.ccrama.redditslide.Fragments.CommentPage) SidebarLayout(me.ccrama.redditslide.Views.SidebarLayout) ApiException(net.dean.jraw.ApiException) Palette(me.ccrama.redditslide.Visuals.Palette) ViewGroup(android.view.ViewGroup) CatchStaggeredGridLayoutManager(me.ccrama.redditslide.Views.CatchStaggeredGridLayoutManager) OfflineSubreddit(me.ccrama.redditslide.OfflineSubreddit) List(java.util.List) TextView(android.widget.TextView) SortingUtil(me.ccrama.redditslide.util.SortingUtil) LinearInterpolator(android.view.animation.LinearInterpolator) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) CommentOverflow(me.ccrama.redditslide.Views.CommentOverflow) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Snackbar(com.google.android.material.snackbar.Snackbar) SubmissionParser(me.ccrama.redditslide.util.SubmissionParser) LayoutUtils(me.ccrama.redditslide.util.LayoutUtils) Context(android.content.Context) DrawerLayout(androidx.drawerlayout.widget.DrawerLayout) SettingValues(me.ccrama.redditslide.SettingValues) AlertDialog(androidx.appcompat.app.AlertDialog) ModerationManager(net.dean.jraw.managers.ModerationManager) Submission(net.dean.jraw.models.Submission) ViewPager(androidx.viewpager.widget.ViewPager) Dialog(android.app.Dialog) Intent(android.content.Intent) HashMap(java.util.HashMap) Constants(me.ccrama.redditslide.Constants) PreCachingLayoutManager(me.ccrama.redditslide.Views.PreCachingLayoutManager) LogUtil(me.ccrama.redditslide.util.LogUtil) MenuItem(android.view.MenuItem) AccountManager(net.dean.jraw.managers.AccountManager) ArrayList(java.util.ArrayList) MiscUtil(me.ccrama.redditslide.util.MiscUtil) MenuInflater(android.view.MenuInflater) UserRecord(net.dean.jraw.models.UserRecord) Toast(android.widget.Toast) Menu(android.view.Menu) UserSubscriptions(me.ccrama.redditslide.UserSubscriptions) MultiRedditUpdateRequest(net.dean.jraw.http.MultiRedditUpdateRequest) DialogInterface(android.content.DialogInterface) TimePeriod(net.dean.jraw.paginators.TimePeriod) StringUtil(me.ccrama.redditslide.util.StringUtil) FragmentManager(androidx.fragment.app.FragmentManager) SettingsSubAdapter(me.ccrama.redditslide.ui.settings.SettingsSubAdapter) Parcelable(android.os.Parcelable) MultiReddit(net.dean.jraw.models.MultiReddit) CompoundButton(android.widget.CompoundButton) FlairTemplate(net.dean.jraw.models.FlairTemplate) LayoutInflater(android.view.LayoutInflater) ImageFlairs(me.ccrama.redditslide.ImageFlairs) Reddit(me.ccrama.redditslide.Reddit) GravityCompat(androidx.core.view.GravityCompat) DialogAction(com.afollestad.materialdialogs.DialogAction) ColorPreferences(me.ccrama.redditslide.Visuals.ColorPreferences) MultiRedditManager(net.dean.jraw.managers.MultiRedditManager) ContextThemeWrapper(androidx.appcompat.view.ContextThemeWrapper) Color(android.graphics.Color) PopupMenu(androidx.appcompat.widget.PopupMenu) Gravity(android.view.Gravity) SharedPreferences(android.content.SharedPreferences) Configuration(android.content.res.Configuration) Subreddit(net.dean.jraw.models.Subreddit) NetworkException(net.dean.jraw.http.NetworkException) HashMap(java.util.HashMap) MultiSubreddit(net.dean.jraw.models.MultiSubreddit) MultiReddit(net.dean.jraw.models.MultiReddit) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) CommentOverflow(me.ccrama.redditslide.Views.CommentOverflow) List(java.util.List) ArrayList(java.util.ArrayList) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) TextView(android.widget.TextView) NetworkException(net.dean.jraw.http.NetworkException) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) AsyncTask(android.os.AsyncTask) Intent(android.content.Intent) ImageView(android.widget.ImageView) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) HorizontalScrollView(android.widget.HorizontalScrollView) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) View(android.view.View) TextView(android.widget.TextView) ApiException(net.dean.jraw.ApiException) NetworkException(net.dean.jraw.http.NetworkException) AppCompatCheckBox(androidx.appcompat.widget.AppCompatCheckBox) MultiRedditManager(net.dean.jraw.managers.MultiRedditManager) AccountManager(net.dean.jraw.managers.AccountManager) CompoundButton(android.widget.CompoundButton) Snackbar(com.google.android.material.snackbar.Snackbar)

Example 4 with R

use of me.ccrama.redditslide.R in project Slide by ccrama.

the class SubmissionNewsAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder2, final int pos) {
    int i = pos != 0 ? pos - 1 : pos;
    if (holder2 instanceof NewsViewHolder) {
        final NewsViewHolder holder = (NewsViewHolder) holder2;
        final Submission submission = dataSet.posts.get(i);
        CreateCardView.colorCard(submission.getSubredditName().toLowerCase(Locale.ENGLISH), holder.itemView, subreddit, (subreddit.equals("frontpage") || subreddit.equals("mod") || subreddit.equals("friends") || (subreddit.equals("all")) || subreddit.contains(".") || subreddit.contains("+")));
        holder.itemView.setOnClickListener(new OnSingleClickListener() {

            @Override
            public void onSingleClick(View v) {
                if (Authentication.didOnline || submission.getComments() != null) {
                    holder.title.setAlpha(0.54f);
                    if (context instanceof MainActivity) {
                        final MainActivity a = (MainActivity) context;
                        if (a.singleMode && a.commentPager && a.adapter instanceof MainActivity.MainPagerAdapterComment) {
                            if (a.openingComments != submission) {
                                clicked = holder2.getBindingAdapterPosition();
                                a.openingComments = submission;
                                a.toOpenComments = a.pager.getCurrentItem() + 1;
                                a.currentComment = holder.getBindingAdapterPosition() - 1;
                                ((MainActivity.MainPagerAdapterComment) (a).adapter).storedFragment = (a).adapter.getCurrentFragment();
                                ((MainActivity.MainPagerAdapterComment) (a).adapter).size = a.toOpenComments + 1;
                                try {
                                    a.adapter.notifyDataSetChanged();
                                } catch (Exception ignored) {
                                }
                            }
                            a.pager.postDelayed(new Runnable() {

                                @Override
                                public void run() {
                                    a.pager.setCurrentItem(a.pager.getCurrentItem() + 1, true);
                                }
                            }, 400);
                        } else {
                            Intent i2 = new Intent(context, CommentsScreen.class);
                            i2.putExtra(CommentsScreen.EXTRA_PAGE, holder2.getBindingAdapterPosition() - 1);
                            i2.putExtra(CommentsScreen.EXTRA_SUBREDDIT, subreddit);
                            i2.putExtra("fullname", submission.getFullName());
                            context.startActivityForResult(i2, 940);
                            clicked = holder2.getBindingAdapterPosition();
                        }
                    } else if (context instanceof SubredditView) {
                        final SubredditView a = (SubredditView) context;
                        if (a.singleMode && a.commentPager) {
                            if (a.openingComments != submission) {
                                clicked = holder2.getBindingAdapterPosition();
                                a.openingComments = submission;
                                a.currentComment = holder.getBindingAdapterPosition() - 1;
                                ((SubredditView.SubredditPagerAdapterComment) (a).adapter).storedFragment = (a).adapter.getCurrentFragment();
                                ((SubredditView.SubredditPagerAdapterComment) a.adapter).size = 3;
                                a.adapter.notifyDataSetChanged();
                            }
                            a.pager.postDelayed(new Runnable() {

                                @Override
                                public void run() {
                                    a.pager.setCurrentItem(a.pager.getCurrentItem() + 1, true);
                                }
                            }, 400);
                        } else {
                            Intent i2 = new Intent(context, CommentsScreen.class);
                            i2.putExtra(CommentsScreen.EXTRA_PAGE, holder2.getBindingAdapterPosition() - 1);
                            i2.putExtra(CommentsScreen.EXTRA_SUBREDDIT, subreddit);
                            i2.putExtra("fullname", submission.getFullName());
                            context.startActivityForResult(i2, 940);
                            clicked = holder2.getBindingAdapterPosition();
                        }
                    }
                } else {
                    if (!Reddit.appRestart.contains("offlinepopup")) {
                        new AlertDialog.Builder(context).setTitle(R.string.cache_no_comments_found).setMessage(R.string.cache_no_comments_found_message).setCancelable(false).setPositiveButton(R.string.btn_ok, (dialog, which) -> Reddit.appRestart.edit().putString("offlinepopup", "").apply()).show();
                    } else {
                        Snackbar s = Snackbar.make(holder.itemView, R.string.cache_no_comments_found_snackbar, Snackbar.LENGTH_SHORT);
                        s.setAction(R.string.misc_more_info, new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                new AlertDialog.Builder(context).setTitle(R.string.cache_no_comments_found).setMessage(R.string.cache_no_comments_found_message).setCancelable(false).setPositiveButton(R.string.btn_ok, (dialog, which) -> Reddit.appRestart.edit().putString("offlinepopup", "").apply()).show();
                            }
                        });
                        LayoutUtils.showSnackbar(s);
                    }
                }
            }
        });
        new PopulateNewsViewHolder().populateNewsViewHolder(holder, submission, context, false, false, dataSet.posts, listView, custom, dataSet.offline, dataSet.subreddit.toLowerCase(Locale.ENGLISH), null);
    }
    if (holder2 instanceof SubmissionFooterViewHolder) {
        Handler handler = new Handler();
        final Runnable r = new Runnable() {

            public void run() {
                notifyItemChanged(dataSet.posts.size() + // the loading spinner to replaced by nomoreposts.xml
                1);
            }
        };
        handler.post(r);
        if (holder2.itemView.findViewById(R.id.reload) != null) {
            holder2.itemView.findViewById(R.id.reload).setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    dataSet.loadMore(context, displayer, true);
                }
            });
        }
    }
    if (holder2 instanceof SpacerViewHolder) {
        View header = (context).findViewById(R.id.header);
        int height = header.getHeight();
        if (height == 0) {
            header.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            height = header.getMeasuredHeight();
            holder2.itemView.findViewById(R.id.height).setLayoutParams(new LinearLayout.LayoutParams(holder2.itemView.getWidth(), height));
            if (listView.getLayoutManager() instanceof CatchStaggeredGridLayoutManager) {
                CatchStaggeredGridLayoutManager.LayoutParams layoutParams = new CatchStaggeredGridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
                layoutParams.setFullSpan(true);
                holder2.itemView.setLayoutParams(layoutParams);
            }
        } else {
            holder2.itemView.findViewById(R.id.height).setLayoutParams(new LinearLayout.LayoutParams(holder2.itemView.getWidth(), height));
            if (listView.getLayoutManager() instanceof CatchStaggeredGridLayoutManager) {
                CatchStaggeredGridLayoutManager.LayoutParams layoutParams = new CatchStaggeredGridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
                layoutParams.setFullSpan(true);
                holder2.itemView.setLayoutParams(layoutParams);
            }
        }
    }
}
Also used : AlertDialog(androidx.appcompat.app.AlertDialog) LayoutUtils(me.ccrama.redditslide.util.LayoutUtils) LinearLayout(android.widget.LinearLayout) SettingValues(me.ccrama.redditslide.SettingValues) AlertDialog(androidx.appcompat.app.AlertDialog) R(me.ccrama.redditslide.R) PopulateNewsViewHolder(me.ccrama.redditslide.SubmissionViews.PopulateNewsViewHolder) Submission(net.dean.jraw.models.Submission) MainActivity(me.ccrama.redditslide.Activities.MainActivity) Intent(android.content.Intent) ArrayList(java.util.ArrayList) OnSingleClickListener(me.ccrama.redditslide.util.OnSingleClickListener) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) Locale(java.util.Locale) Handler(android.os.Handler) SubredditView(me.ccrama.redditslide.Activities.SubredditView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) CommentsScreen(me.ccrama.redditslide.Activities.CommentsScreen) LayoutInflater(android.view.LayoutInflater) Reddit(me.ccrama.redditslide.Reddit) Authentication(me.ccrama.redditslide.Authentication) ViewGroup(android.view.ViewGroup) CatchStaggeredGridLayoutManager(me.ccrama.redditslide.Views.CatchStaggeredGridLayoutManager) List(java.util.List) CreateCardView(me.ccrama.redditslide.Views.CreateCardView) Activity(android.app.Activity) Snackbar(com.google.android.material.snackbar.Snackbar) CatchStaggeredGridLayoutManager(me.ccrama.redditslide.Views.CatchStaggeredGridLayoutManager) OnSingleClickListener(me.ccrama.redditslide.util.OnSingleClickListener) SubredditView(me.ccrama.redditslide.Activities.SubredditView) MainActivity(me.ccrama.redditslide.Activities.MainActivity) PopulateNewsViewHolder(me.ccrama.redditslide.SubmissionViews.PopulateNewsViewHolder) CommentsScreen(me.ccrama.redditslide.Activities.CommentsScreen) Submission(net.dean.jraw.models.Submission) Handler(android.os.Handler) Intent(android.content.Intent) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) SubredditView(me.ccrama.redditslide.Activities.SubredditView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) CreateCardView(me.ccrama.redditslide.Views.CreateCardView) PopulateNewsViewHolder(me.ccrama.redditslide.SubmissionViews.PopulateNewsViewHolder) LinearLayout(android.widget.LinearLayout) Snackbar(com.google.android.material.snackbar.Snackbar)

Example 5 with R

use of me.ccrama.redditslide.R in project Slide by ccrama.

the class PopulateSubmissionViewHolder method showBottomSheet.

public <T extends Contribution> void showBottomSheet(final Activity mContext, final Submission submission, final SubmissionViewHolder holder, final List<T> posts, final String baseSub, final RecyclerView recyclerview, final boolean full) {
    int[] attrs = new int[] { R.attr.tintColor };
    TypedArray ta = mContext.obtainStyledAttributes(attrs);
    int color = ta.getColor(0, Color.WHITE);
    Drawable profile = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_account_circle, null);
    final Drawable sub = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_bookmark_border, null);
    Drawable saved = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_star, null);
    Drawable hide = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_visibility_off, null);
    final Drawable report = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_report, null);
    Drawable copy = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_content_copy, null);
    final Drawable readLater = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_download, null);
    Drawable open = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_open_in_browser, null);
    Drawable link = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_link, null);
    Drawable reddit = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_forum, null);
    Drawable filter = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_filter_list, null);
    Drawable crosspost = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_forward, null);
    final List<Drawable> drawableSet = Arrays.asList(profile, sub, saved, hide, report, copy, open, link, reddit, readLater, filter, crosspost);
    BlendModeUtil.tintDrawablesAsSrcAtop(drawableSet, color);
    ta.recycle();
    final BottomSheet.Builder b = new BottomSheet.Builder(mContext).title(CompatUtil.fromHtml(submission.getTitle()));
    final boolean isReadLater = mContext instanceof PostReadLater;
    final boolean isAddedToReadLaterList = ReadLater.isToBeReadLater(submission);
    if (Authentication.didOnline) {
        b.sheet(1, profile, "/u/" + submission.getAuthor()).sheet(2, sub, "/r/" + submission.getSubredditName());
        String save = mContext.getString(R.string.btn_save);
        if (ActionStates.isSaved(submission)) {
            save = mContext.getString(R.string.comment_unsave);
        }
        if (Authentication.isLoggedIn) {
            b.sheet(3, saved, save);
        }
    }
    if (isAddedToReadLaterList) {
        b.sheet(28, readLater, "Mark As Read");
    } else {
        b.sheet(28, readLater, "Read later");
    }
    if (Authentication.didOnline) {
        if (Authentication.isLoggedIn) {
            b.sheet(12, report, mContext.getString(R.string.btn_report));
            b.sheet(13, crosspost, mContext.getString(R.string.btn_crosspost));
        }
    }
    if (submission.getSelftext() != null && !submission.getSelftext().isEmpty() && full) {
        b.sheet(25, copy, mContext.getString(R.string.submission_copy_text));
    }
    boolean hidden = submission.isHidden();
    if (!full && Authentication.didOnline) {
        if (!hidden) {
            b.sheet(5, hide, mContext.getString(R.string.submission_hide));
        } else {
            b.sheet(5, hide, mContext.getString(R.string.submission_unhide));
        }
    }
    b.sheet(7, open, mContext.getString(R.string.open_externally));
    b.sheet(4, link, mContext.getString(R.string.submission_share_permalink)).sheet(8, reddit, mContext.getString(R.string.submission_share_reddit_url));
    if ((mContext instanceof MainActivity) || (mContext instanceof SubredditView)) {
        b.sheet(10, filter, mContext.getString(R.string.filter_content));
    }
    b.listener(new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch(which) {
                case 1:
                    {
                        Intent i = new Intent(mContext, Profile.class);
                        i.putExtra(Profile.EXTRA_PROFILE, submission.getAuthor());
                        mContext.startActivity(i);
                    }
                    break;
                case 2:
                    {
                        Intent i = new Intent(mContext, SubredditView.class);
                        i.putExtra(SubredditView.EXTRA_SUBREDDIT, submission.getSubredditName());
                        mContext.startActivityForResult(i, 14);
                    }
                    break;
                case 10:
                    String[] choices;
                    final String flair = submission.getSubmissionFlair().getText() != null ? submission.getSubmissionFlair().getText() : "";
                    if (flair.isEmpty()) {
                        choices = new String[] { mContext.getString(R.string.filter_posts_sub, submission.getSubredditName()), mContext.getString(R.string.filter_posts_user, submission.getAuthor()), mContext.getString(R.string.filter_posts_urls, submission.getDomain()), mContext.getString(R.string.filter_open_externally, submission.getDomain()) };
                        chosen = new boolean[] { SettingValues.subredditFilters.contains(submission.getSubredditName().toLowerCase(Locale.ENGLISH)), SettingValues.userFilters.contains(submission.getAuthor().toLowerCase(Locale.ENGLISH)), SettingValues.domainFilters.contains(submission.getDomain().toLowerCase(Locale.ENGLISH)), SettingValues.alwaysExternal.contains(submission.getDomain().toLowerCase(Locale.ENGLISH)) };
                        oldChosen = chosen.clone();
                    } else {
                        choices = new String[] { mContext.getString(R.string.filter_posts_sub, submission.getSubredditName()), mContext.getString(R.string.filter_posts_user, submission.getAuthor()), mContext.getString(R.string.filter_posts_urls, submission.getDomain()), mContext.getString(R.string.filter_open_externally, submission.getDomain()), mContext.getString(R.string.filter_posts_flair, flair, baseSub) };
                    }
                    chosen = new boolean[] { SettingValues.subredditFilters.contains(submission.getSubredditName().toLowerCase(Locale.ENGLISH)), SettingValues.userFilters.contains(submission.getAuthor().toLowerCase(Locale.ENGLISH)), SettingValues.domainFilters.contains(submission.getDomain().toLowerCase(Locale.ENGLISH)), SettingValues.alwaysExternal.contains(submission.getDomain().toLowerCase(Locale.ENGLISH)), SettingValues.flairFilters.contains(baseSub + ":" + flair.toLowerCase(Locale.ENGLISH).trim()) };
                    oldChosen = chosen.clone();
                    new AlertDialog.Builder(mContext).setTitle(R.string.filter_title).setMultiChoiceItems(choices, chosen, (dialog1, which1, isChecked) -> chosen[which1] = isChecked).setPositiveButton(R.string.filter_btn, (dialog12, which12) -> {
                        boolean filtered = false;
                        SharedPreferences.Editor e = SettingValues.prefs.edit();
                        if (chosen[0] && chosen[0] != oldChosen[0]) {
                            SettingValues.subredditFilters.add(submission.getSubredditName().toLowerCase(Locale.ENGLISH).trim());
                            filtered = true;
                            e.putStringSet(SettingValues.PREF_SUBREDDIT_FILTERS, SettingValues.subredditFilters);
                        } else if (!chosen[0] && chosen[0] != oldChosen[0]) {
                            SettingValues.subredditFilters.remove(submission.getSubredditName().toLowerCase(Locale.ENGLISH).trim());
                            filtered = false;
                            e.putStringSet(SettingValues.PREF_SUBREDDIT_FILTERS, SettingValues.subredditFilters);
                            e.apply();
                        }
                        if (chosen[1] && chosen[1] != oldChosen[1]) {
                            SettingValues.userFilters.add(submission.getAuthor().toLowerCase(Locale.ENGLISH).trim());
                            filtered = true;
                            e.putStringSet(SettingValues.PREF_USER_FILTERS, SettingValues.userFilters);
                        } else if (!chosen[1] && chosen[1] != oldChosen[1]) {
                            SettingValues.userFilters.remove(submission.getAuthor().toLowerCase(Locale.ENGLISH).trim());
                            filtered = false;
                            e.putStringSet(SettingValues.PREF_USER_FILTERS, SettingValues.userFilters);
                            e.apply();
                        }
                        if (chosen[2] && chosen[2] != oldChosen[2]) {
                            SettingValues.domainFilters.add(submission.getDomain().toLowerCase(Locale.ENGLISH).trim());
                            filtered = true;
                            e.putStringSet(SettingValues.PREF_DOMAIN_FILTERS, SettingValues.domainFilters);
                        } else if (!chosen[2] && chosen[2] != oldChosen[2]) {
                            SettingValues.domainFilters.remove(submission.getDomain().toLowerCase(Locale.ENGLISH).trim());
                            filtered = false;
                            e.putStringSet(SettingValues.PREF_DOMAIN_FILTERS, SettingValues.domainFilters);
                            e.apply();
                        }
                        if (chosen[3] && chosen[3] != oldChosen[3]) {
                            SettingValues.alwaysExternal.add(submission.getDomain().toLowerCase(Locale.ENGLISH).trim());
                            e.putStringSet(SettingValues.PREF_ALWAYS_EXTERNAL, SettingValues.alwaysExternal);
                            e.apply();
                        } else if (!chosen[3] && chosen[3] != oldChosen[3]) {
                            SettingValues.alwaysExternal.remove(submission.getDomain().toLowerCase(Locale.ENGLISH).trim());
                            e.putStringSet(SettingValues.PREF_ALWAYS_EXTERNAL, SettingValues.alwaysExternal);
                            e.apply();
                        }
                        if (chosen.length > 4) {
                            String s = (baseSub + ":" + flair).toLowerCase(Locale.ENGLISH).trim();
                            if (chosen[4] && chosen[4] != oldChosen[4]) {
                                SettingValues.flairFilters.add(s);
                                e.putStringSet(SettingValues.PREF_FLAIR_FILTERS, SettingValues.flairFilters);
                                e.apply();
                                filtered = true;
                            } else if (!chosen[4] && chosen[4] != oldChosen[4]) {
                                SettingValues.flairFilters.remove(s);
                                e.putStringSet(SettingValues.PREF_FLAIR_FILTERS, SettingValues.flairFilters);
                                e.apply();
                            }
                        }
                        if (filtered) {
                            e.apply();
                            ArrayList<Contribution> toRemove = new ArrayList<>();
                            for (Contribution s : posts) {
                                if (s instanceof Submission && PostMatch.doesMatch((Submission) s)) {
                                    toRemove.add(s);
                                }
                            }
                            OfflineSubreddit s = OfflineSubreddit.getSubreddit(baseSub, false, mContext);
                            for (Contribution remove : toRemove) {
                                final int pos = posts.indexOf(remove);
                                posts.remove(pos);
                                if (baseSub != null) {
                                    s.hideMulti(pos);
                                }
                            }
                            s.writeToMemoryNoStorage();
                            recyclerview.getAdapter().notifyDataSetChanged();
                        }
                    }).setNegativeButton(R.string.btn_cancel, null).show();
                    break;
                case 3:
                    saveSubmission(submission, mContext, holder, full);
                    break;
                case 5:
                    {
                        hideSubmission(submission, posts, baseSub, recyclerview, mContext);
                    }
                    break;
                case 7:
                    LinkUtil.openExternally(submission.getUrl());
                    if (submission.isNsfw() && !SettingValues.storeNSFWHistory) {
                    // Do nothing if the post is NSFW and storeNSFWHistory is not enabled
                    } else if (SettingValues.storeHistory) {
                        HasSeen.addSeen(submission.getFullName());
                    }
                    break;
                case 13:
                    LinkUtil.crosspost(submission, mContext);
                    break;
                case 28:
                    if (!isAddedToReadLaterList) {
                        ReadLater.setReadLater(submission, true);
                        Snackbar s = Snackbar.make(holder.itemView, "Added to read later!", Snackbar.LENGTH_SHORT);
                        View view = s.getView();
                        TextView tv = view.findViewById(com.google.android.material.R.id.snackbar_text);
                        tv.setTextColor(Color.WHITE);
                        s.setAction(R.string.btn_undo, new View.OnClickListener() {

                            @Override
                            public void onClick(View view) {
                                ReadLater.setReadLater(submission, false);
                                Snackbar s2 = Snackbar.make(holder.itemView, "Removed from read later", Snackbar.LENGTH_SHORT);
                                LayoutUtils.showSnackbar(s2);
                            }
                        });
                        if (NetworkUtil.isConnected(mContext)) {
                            new CommentCacheAsync(Collections.singletonList(submission), mContext, CommentCacheAsync.SAVED_SUBMISSIONS, new boolean[] { true, true }).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        }
                        s.show();
                    } else {
                        ReadLater.setReadLater(submission, false);
                        if (isReadLater || !Authentication.didOnline) {
                            final int pos = posts.indexOf(submission);
                            posts.remove(submission);
                            recyclerview.getAdapter().notifyItemRemoved(holder.getBindingAdapterPosition());
                            Snackbar s2 = Snackbar.make(holder.itemView, "Removed from read later", Snackbar.LENGTH_SHORT);
                            View view2 = s2.getView();
                            TextView tv2 = view2.findViewById(com.google.android.material.R.id.snackbar_text);
                            tv2.setTextColor(Color.WHITE);
                            s2.setAction(R.string.btn_undo, new View.OnClickListener() {

                                @Override
                                public void onClick(View view) {
                                    posts.add(pos, (T) submission);
                                    recyclerview.getAdapter().notifyDataSetChanged();
                                }
                            });
                        } else {
                            Snackbar s2 = Snackbar.make(holder.itemView, "Removed from read later", Snackbar.LENGTH_SHORT);
                            View view2 = s2.getView();
                            TextView tv2 = view2.findViewById(com.google.android.material.R.id.snackbar_text);
                            s2.show();
                        }
                        OfflineSubreddit.newSubreddit(CommentCacheAsync.SAVED_SUBMISSIONS).deleteFromMemory(submission.getFullName());
                    }
                    break;
                case 4:
                    Reddit.defaultShareText(CompatUtil.fromHtml(submission.getTitle()).toString(), StringEscapeUtils.escapeHtml4(submission.getUrl()), mContext);
                    break;
                case 12:
                    final MaterialDialog reportDialog = new MaterialDialog.Builder(mContext).customView(R.layout.report_dialog, true).title(R.string.report_post).positiveText(R.string.btn_report).negativeText(R.string.btn_cancel).onPositive(new MaterialDialog.SingleButtonCallback() {

                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {
                            RadioGroup reasonGroup = dialog.getCustomView().findViewById(R.id.report_reasons);
                            String reportReason;
                            if (reasonGroup.getCheckedRadioButtonId() == R.id.report_other) {
                                reportReason = ((EditText) dialog.getCustomView().findViewById(R.id.input_report_reason)).getText().toString();
                            } else {
                                reportReason = ((RadioButton) reasonGroup.findViewById(reasonGroup.getCheckedRadioButtonId())).getText().toString();
                            }
                            new AsyncReportTask(submission, holder.itemView).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, reportReason);
                        }
                    }).build();
                    final RadioGroup reasonGroup = reportDialog.getCustomView().findViewById(R.id.report_reasons);
                    reasonGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

                        @Override
                        public void onCheckedChanged(RadioGroup group, int checkedId) {
                            if (checkedId == R.id.report_other)
                                reportDialog.getCustomView().findViewById(R.id.input_report_reason).setVisibility(View.VISIBLE);
                            else
                                reportDialog.getCustomView().findViewById(R.id.input_report_reason).setVisibility(View.GONE);
                        }
                    });
                    // Load sub's report reasons and show the appropriate ones
                    new AsyncTask<Void, Void, Ruleset>() {

                        @Override
                        protected Ruleset doInBackground(Void... voids) {
                            return Authentication.reddit.getRules(submission.getSubredditName());
                        }

                        @Override
                        protected void onPostExecute(Ruleset rules) {
                            reportDialog.getCustomView().findViewById(R.id.report_loading).setVisibility(View.GONE);
                            if (rules.getSubredditRules().size() > 0) {
                                TextView subHeader = new TextView(mContext);
                                subHeader.setText(mContext.getString(R.string.report_sub_rules, submission.getSubredditName()));
                                reasonGroup.addView(subHeader, reasonGroup.getChildCount() - 2);
                            }
                            for (SubredditRule rule : rules.getSubredditRules()) {
                                if (rule.getKind() == SubredditRule.RuleKind.LINK || rule.getKind() == SubredditRule.RuleKind.ALL) {
                                    RadioButton btn = new RadioButton(mContext);
                                    btn.setText(rule.getViolationReason());
                                    reasonGroup.addView(btn, reasonGroup.getChildCount() - 2);
                                    btn.getLayoutParams().width = WindowManager.LayoutParams.MATCH_PARENT;
                                }
                            }
                            if (rules.getSiteRules().size() > 0) {
                                TextView siteHeader = new TextView(mContext);
                                siteHeader.setText(R.string.report_site_rules);
                                reasonGroup.addView(siteHeader, reasonGroup.getChildCount() - 2);
                            }
                            for (String rule : rules.getSiteRules()) {
                                RadioButton btn = new RadioButton(mContext);
                                btn.setText(rule);
                                reasonGroup.addView(btn, reasonGroup.getChildCount() - 2);
                                btn.getLayoutParams().width = WindowManager.LayoutParams.MATCH_PARENT;
                            }
                        }
                    }.execute();
                    reportDialog.show();
                    break;
                case 8:
                    if (SettingValues.shareLongLink) {
                        Reddit.defaultShareText(submission.getTitle(), "https://reddit.com" + submission.getPermalink(), mContext);
                    } else {
                        Reddit.defaultShareText(submission.getTitle(), "https://redd.it/" + submission.getId(), mContext);
                    }
                    break;
                case 6:
                    {
                        ClipboardUtil.copyToClipboard(mContext, "Link", submission.getUrl());
                        Toast.makeText(mContext, R.string.submission_link_copied, Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 25:
                    final TextView showText = new TextView(mContext);
                    showText.setText(StringEscapeUtils.unescapeHtml4(submission.getTitle() + "\n\n" + submission.getSelftext()));
                    showText.setTextIsSelectable(true);
                    int sixteen = DisplayUtil.dpToPxVertical(24);
                    showText.setPadding(sixteen, 0, sixteen, 0);
                    new AlertDialog.Builder(mContext).setView(showText).setTitle("Select text to copy").setCancelable(true).setPositiveButton("COPY SELECTED", (dialog13, which13) -> {
                        String selected = showText.getText().toString().substring(showText.getSelectionStart(), showText.getSelectionEnd());
                        if (!selected.isEmpty()) {
                            ClipboardUtil.copyToClipboard(mContext, "Selftext", selected);
                        } else {
                            ClipboardUtil.copyToClipboard(mContext, "Selftext", CompatUtil.fromHtml(submission.getTitle() + "\n\n" + submission.getSelftext()));
                        }
                        Toast.makeText(mContext, R.string.submission_comment_copied, Toast.LENGTH_SHORT).show();
                    }).setNegativeButton(R.string.btn_cancel, null).setNeutralButton("COPY ALL", (dialog14, which14) -> {
                        ClipboardUtil.copyToClipboard(mContext, "Selftext", StringEscapeUtils.unescapeHtml4(submission.getTitle() + "\n\n" + submission.getSelftext()));
                        Toast.makeText(mContext, R.string.submission_text_copied, Toast.LENGTH_SHORT).show();
                    }).show();
                    break;
            }
        }
    });
    b.show();
}
Also used : Arrays(java.util.Arrays) Bundle(android.os.Bundle) R(me.ccrama.redditslide.R) RobotoTypefaces(com.devspark.robototextview.RobotoTypefaces) Thing(net.dean.jraw.models.Thing) MainActivity(me.ccrama.redditslide.Activities.MainActivity) MediaView(me.ccrama.redditslide.Activities.MediaView) AnimatorUtil(me.ccrama.redditslide.util.AnimatorUtil) JsonUtil(me.ccrama.redditslide.util.JsonUtil) ImageView(android.widget.ImageView) RadioButton(android.widget.RadioButton) DistinguishedStatus(net.dean.jraw.models.DistinguishedStatus) PostMatch(me.ccrama.redditslide.PostMatch) ContentType(me.ccrama.redditslide.ContentType) AbsoluteSizeSpan(android.text.style.AbsoluteSizeSpan) DataShare(me.ccrama.redditslide.DataShare) Drawable(android.graphics.drawable.Drawable) AppCompatActivity(androidx.appcompat.app.AppCompatActivity) OnSingleClickListener(me.ccrama.redditslide.util.OnSingleClickListener) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) MultiredditOverview(me.ccrama.redditslide.Activities.MultiredditOverview) ContextCompat(androidx.core.content.ContextCompat) Ruleset(net.dean.jraw.models.Ruleset) DisplayUtil(me.ccrama.redditslide.util.DisplayUtil) GalleryImage(me.ccrama.redditslide.Activities.GalleryImage) Palette(me.ccrama.redditslide.Visuals.Palette) BlendModeUtil(me.ccrama.redditslide.util.BlendModeUtil) Profile(me.ccrama.redditslide.Activities.Profile) PeekViewActivity(me.ccrama.redditslide.ForceTouch.PeekViewActivity) Nullable(androidx.annotation.Nullable) Contribution(net.dean.jraw.models.Contribution) Reauthenticate(me.ccrama.redditslide.Activities.Reauthenticate) SubmissionParser(me.ccrama.redditslide.util.SubmissionParser) DoEditorActions(me.ccrama.redditslide.Views.DoEditorActions) HasSeen(me.ccrama.redditslide.HasSeen) Vote(me.ccrama.redditslide.Vote) Dialog(android.app.Dialog) SubmissionViewHolder(me.ccrama.redditslide.Adapters.SubmissionViewHolder) RadioGroup(android.widget.RadioGroup) AccountManager(net.dean.jraw.managers.AccountManager) ArrayList(java.util.ArrayList) SpannableStringBuilder(android.text.SpannableStringBuilder) TumblrPager(me.ccrama.redditslide.Activities.TumblrPager) Toast(android.widget.Toast) UserSubscriptions(me.ccrama.redditslide.UserSubscriptions) OpenRedditLink(me.ccrama.redditslide.OpenRedditLink) InvalidScopeException(net.dean.jraw.http.oauth.InvalidScopeException) FluentRedditClient(net.dean.jraw.fluent.FluentRedditClient) FlairTemplate(net.dean.jraw.models.FlairTemplate) Reddit(me.ccrama.redditslide.Reddit) VoteDirection(net.dean.jraw.models.VoteDirection) ModQueue(me.ccrama.redditslide.Activities.ModQueue) SharedPreferences(android.content.SharedPreferences) CreateCardView(me.ccrama.redditslide.Views.CreateCardView) GifUtils(me.ccrama.redditslide.util.GifUtils) ActionStates(me.ccrama.redditslide.ActionStates) EditText(android.widget.EditText) LinkUtil(me.ccrama.redditslide.util.LinkUtil) EXTRA_SUBMISSION_TITLE(me.ccrama.redditslide.Notifications.ImageDownloadNotificationService.EXTRA_SUBMISSION_TITLE) LinearLayout(android.widget.LinearLayout) CommentCacheAsync(me.ccrama.redditslide.CommentCacheAsync) WindowManager(android.view.WindowManager) Tumblr(me.ccrama.redditslide.Activities.Tumblr) Locale(java.util.Locale) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) SubredditRule(net.dean.jraw.models.SubredditRule) ToolboxUI(me.ccrama.redditslide.Toolbox.ToolboxUI) AsyncTask(android.os.AsyncTask) FullscreenVideo(me.ccrama.redditslide.Activities.FullscreenVideo) Album(me.ccrama.redditslide.Activities.Album) Authentication(me.ccrama.redditslide.Authentication) InputType(android.text.InputType) ApiException(net.dean.jraw.ApiException) SubmissionCache(me.ccrama.redditslide.SubmissionCache) AlbumPager(me.ccrama.redditslide.Activities.AlbumPager) OfflineSubreddit(me.ccrama.redditslide.OfflineSubreddit) List(java.util.List) NetworkUtil(me.ccrama.redditslide.util.NetworkUtil) TextView(android.widget.TextView) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Snackbar(com.google.android.material.snackbar.Snackbar) BottomSheet(com.cocosw.bottomsheet.BottomSheet) RedditGalleryPager(me.ccrama.redditslide.Activities.RedditGalleryPager) Typeface(android.graphics.Typeface) LayoutUtils(me.ccrama.redditslide.util.LayoutUtils) Context(android.content.Context) SettingValues(me.ccrama.redditslide.SettingValues) AlertDialog(androidx.appcompat.app.AlertDialog) ResourcesCompat(androidx.core.content.res.ResourcesCompat) ModerationManager(net.dean.jraw.managers.ModerationManager) FontPreferences(me.ccrama.redditslide.Visuals.FontPreferences) Submission(net.dean.jraw.models.Submission) Intent(android.content.Intent) Hidden(me.ccrama.redditslide.Hidden) TypedArray(android.content.res.TypedArray) Search(me.ccrama.redditslide.Activities.Search) SubredditView(me.ccrama.redditslide.Activities.SubredditView) DialogInterface(android.content.DialogInterface) ClipboardUtil(me.ccrama.redditslide.util.ClipboardUtil) LayoutInflater(android.view.LayoutInflater) DialogAction(com.afollestad.materialdialogs.DialogAction) StringEscapeUtils(org.apache.commons.text.StringEscapeUtils) CompatUtil(me.ccrama.redditslide.util.CompatUtil) Color(android.graphics.Color) FlairReference(net.dean.jraw.fluent.FlairReference) RedditGallery(me.ccrama.redditslide.Activities.RedditGallery) PostReadLater(me.ccrama.redditslide.Activities.PostReadLater) CommentAdapter(me.ccrama.redditslide.Adapters.CommentAdapter) LastComments(me.ccrama.redditslide.LastComments) Activity(android.app.Activity) NetworkException(net.dean.jraw.http.NetworkException) Collections(java.util.Collections) Resources(android.content.res.Resources) Ruleset(net.dean.jraw.models.Ruleset) RadioGroup(android.widget.RadioGroup) DialogInterface(android.content.DialogInterface) SpannableStringBuilder(android.text.SpannableStringBuilder) ArrayList(java.util.ArrayList) PostReadLater(me.ccrama.redditslide.Activities.PostReadLater) SubredditView(me.ccrama.redditslide.Activities.SubredditView) MainActivity(me.ccrama.redditslide.Activities.MainActivity) TypedArray(android.content.res.TypedArray) TextView(android.widget.TextView) SubredditRule(net.dean.jraw.models.SubredditRule) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Submission(net.dean.jraw.models.Submission) CommentCacheAsync(me.ccrama.redditslide.CommentCacheAsync) Drawable(android.graphics.drawable.Drawable) OfflineSubreddit(me.ccrama.redditslide.OfflineSubreddit) AsyncTask(android.os.AsyncTask) Intent(android.content.Intent) RadioButton(android.widget.RadioButton) MediaView(me.ccrama.redditslide.Activities.MediaView) ImageView(android.widget.ImageView) CreateCardView(me.ccrama.redditslide.Views.CreateCardView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) TextView(android.widget.TextView) SubredditView(me.ccrama.redditslide.Activities.SubredditView) DialogAction(com.afollestad.materialdialogs.DialogAction) BottomSheet(com.cocosw.bottomsheet.BottomSheet) Contribution(net.dean.jraw.models.Contribution) Snackbar(com.google.android.material.snackbar.Snackbar)

Aggregations

View (android.view.View)9 AlertDialog (androidx.appcompat.app.AlertDialog)9 ArrayList (java.util.ArrayList)9 R (me.ccrama.redditslide.R)9 SettingValues (me.ccrama.redditslide.SettingValues)9 LayoutInflater (android.view.LayoutInflater)8 Reddit (me.ccrama.redditslide.Reddit)8 Activity (android.app.Activity)7 ViewGroup (android.view.ViewGroup)7 Snackbar (com.google.android.material.snackbar.Snackbar)7 List (java.util.List)7 Locale (java.util.Locale)7 Authentication (me.ccrama.redditslide.Authentication)7 Context (android.content.Context)6 Intent (android.content.Intent)6 RecyclerView (androidx.recyclerview.widget.RecyclerView)6 LayoutUtils (me.ccrama.redditslide.util.LayoutUtils)6 OnSingleClickListener (me.ccrama.redditslide.util.OnSingleClickListener)6 Submission (net.dean.jraw.models.Submission)6 AsyncTask (android.os.AsyncTask)5