Search in sources :

Example 11 with OnSingleClickListener

use of me.ccrama.redditslide.util.OnSingleClickListener in project Slide by ccrama.

the class CommentAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder firstHolder, int old) {
    int pos = old != 0 ? old - 1 : old;
    if (firstHolder instanceof CommentViewHolder) {
        final CommentViewHolder holder = (CommentViewHolder) firstHolder;
        int datasetPosition = pos - 1;
        datasetPosition = getRealPosition(datasetPosition);
        if (pos > toShiftTo) {
            shifted = 0;
        }
        if (pos < shiftFrom) {
            shifted = 0;
        }
        final CommentNode baseNode = currentComments.get(datasetPosition).comment;
        final Comment comment = baseNode.getComment();
        if (pos == getItemCount() - 1) {
            holder.itemView.setPadding(0, 0, 0, (int) mContext.getResources().getDimension(R.dimen.overview_top_padding_single));
        } else {
            holder.itemView.setPadding(0, 0, 0, 0);
        }
        doScoreText(holder, comment, this);
        // Long click listeners
        View.OnLongClickListener onLongClickListener = new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                if (SettingValues.swap) {
                    doOnClick(holder, comment, baseNode);
                } else {
                    doLongClick(holder, comment, baseNode);
                }
                return true;
            }
        };
        holder.firstTextView.setOnLongClickListener(onLongClickListener);
        holder.commentOverflow.setOnLongClickListener(onLongClickListener);
        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                if (!currentlyEditingId.equals(comment.getFullName())) {
                    if (SettingValues.swap) {
                        doOnClick(holder, comment, baseNode);
                    } else {
                        doLongClick(holder, comment, baseNode);
                    }
                }
                return true;
            }
        });
        // Single click listeners
        OnSingleClickListener singleClick = new OnSingleClickListener() {

            @Override
            public void onSingleClick(View v) {
                if (!currentlyEditingId.equals(comment.getFullName())) {
                    if (SettingValues.swap) {
                        doLongClick(holder, comment, baseNode);
                    } else {
                        doOnClick(holder, comment, baseNode);
                    }
                }
            }
        };
        holder.itemView.setOnClickListener(singleClick);
        holder.commentOverflow.setOnClickListener(singleClick);
        if (!toCollapse.contains(comment.getFullName()) && SettingValues.collapseComments || !SettingValues.collapseComments) {
            setViews(comment.getDataNode().get("body_html").asText(), submission.getSubredditName(), holder, singleClick, onLongClickListener);
        }
        holder.firstTextView.setOnClickListener(new OnSingleClickListener() {

            @Override
            public void onSingleClick(View v) {
                SpoilerRobotoTextView SpoilerRobotoTextView = (SpoilerRobotoTextView) v;
                if (SettingValues.swap) {
                    if (!SpoilerRobotoTextView.isSpoilerClicked()) {
                        doLongClick(holder, comment, baseNode);
                    } else if (SpoilerRobotoTextView.isSpoilerClicked()) {
                        SpoilerRobotoTextView.resetSpoilerClicked();
                    }
                } else if (!SpoilerRobotoTextView.isSpoilerClicked()) {
                    doOnClick(holder, comment, baseNode);
                } else if (SpoilerRobotoTextView.isSpoilerClicked()) {
                    SpoilerRobotoTextView.resetSpoilerClicked();
                }
            }
        });
        if (ImageFlairs.isSynced(comment.getSubredditName()) && comment.getAuthorFlair() != null && !comment.getAuthorFlair().getText().isEmpty() && !comment.getAuthorFlair().getCssClass().isEmpty()) {
            boolean set = false;
            for (String s : comment.getAuthorFlair().getCssClass().split(" ")) {
                File file = DiskCacheUtils.findInCache(comment.getSubredditName().toLowerCase(Locale.ENGLISH) + ":" + s.toLowerCase(Locale.ENGLISH), ImageFlairs.getFlairImageLoader(mContext).getInstance().getDiskCache());
                if (file != null && file.exists()) {
                    set = true;
                    holder.imageFlair.setVisibility(View.VISIBLE);
                    String decodedImgUri = Uri.fromFile(file).toString();
                    ImageFlairs.getFlairImageLoader(mContext).displayImage(decodedImgUri, holder.imageFlair);
                    break;
                }
            }
            if (!set) {
                holder.imageFlair.setImageDrawable(null);
                holder.imageFlair.setVisibility(View.GONE);
            }
        } else {
            holder.imageFlair.setVisibility(View.GONE);
        }
        // Set typeface for body
        int type = new FontPreferences(mContext).getFontTypeComment().getTypeface();
        Typeface typeface;
        if (type >= 0) {
            typeface = RobotoTypefaces.obtainTypeface(mContext, type);
        } else {
            typeface = Typeface.DEFAULT;
        }
        holder.firstTextView.setTypeface(typeface);
        // Show padding on top
        if (baseNode.isTopLevel()) {
            holder.itemView.findViewById(R.id.next).setVisibility(View.VISIBLE);
        } else if (holder.itemView.findViewById(R.id.next).getVisibility() == View.VISIBLE) {
            holder.itemView.findViewById(R.id.next).setVisibility(View.GONE);
        }
        // Should be collapsed?
        if (hiddenPersons.contains(comment.getFullName()) || toCollapse.contains(comment.getFullName())) {
            int childnumber = getChildNumber(baseNode);
            if (hiddenPersons.contains(comment.getFullName()) && childnumber > 0) {
                holder.childrenNumber.setVisibility(View.VISIBLE);
                holder.childrenNumber.setText("+" + childnumber);
            } else {
                holder.childrenNumber.setVisibility(View.GONE);
            }
            if (SettingValues.collapseComments && toCollapse.contains(comment.getFullName())) {
                holder.firstTextView.setVisibility(View.GONE);
                holder.commentOverflow.setVisibility(View.GONE);
            }
        } else {
            holder.childrenNumber.setVisibility(View.GONE);
            holder.commentOverflow.setVisibility(View.VISIBLE);
        }
        holder.dot.setVisibility(View.VISIBLE);
        int dwidth = (int) ((SettingValues.largeDepth ? 5 : 3) * Resources.getSystem().getDisplayMetrics().density);
        int width = 0;
        // Padding on the left, starting with the third comment
        for (int i = 2; i < baseNode.getDepth(); i++) {
            width += dwidth;
        }
        RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();
        params.setMargins(width, 0, 0, 0);
        holder.itemView.setLayoutParams(params);
        RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) holder.dot.getLayoutParams();
        params2.width = dwidth;
        holder.dot.setLayoutParams(params2);
        if (baseNode.getDepth() - 1 > 0) {
            int i22 = baseNode.getDepth() - 2;
            String commentOp = dataSet.commentOPs.get(comment.getId());
            if (SettingValues.highlightCommentOP && commentOp != null && comment != null && commentOp.equals(comment.getAuthor())) {
                holder.dot.setBackgroundColor(ContextCompat.getColor(mContext, R.color.md_purple_500));
            } else {
                if (i22 % 5 == 0) {
                    holder.dot.setBackgroundColor(ContextCompat.getColor(mContext, !SettingValues.colorCommentDepth ? R.color.md_grey_700 : R.color.md_blue_500));
                } else if (i22 % 4 == 0) {
                    holder.dot.setBackgroundColor(ContextCompat.getColor(mContext, !SettingValues.colorCommentDepth ? R.color.md_grey_600 : R.color.md_green_500));
                } else if (i22 % 3 == 0) {
                    holder.dot.setBackgroundColor(ContextCompat.getColor(mContext, !SettingValues.colorCommentDepth ? R.color.md_grey_500 : R.color.md_yellow_500));
                } else if (i22 % 2 == 0) {
                    holder.dot.setBackgroundColor(ContextCompat.getColor(mContext, !SettingValues.colorCommentDepth ? R.color.md_grey_400 : R.color.md_orange_500));
                } else {
                    holder.dot.setBackgroundColor(ContextCompat.getColor(mContext, !SettingValues.colorCommentDepth ? R.color.md_grey_300 : R.color.md_red_500));
                }
            }
        } else {
            holder.dot.setVisibility(View.GONE);
        }
        if (currentSelectedItem != null && comment.getFullName().contains(currentSelectedItem) && !currentSelectedItem.isEmpty() && !currentlyEditingId.equals(comment.getFullName())) {
            doHighlighted(holder, comment, baseNode, false);
        } else if (!currentlyEditingId.equals(comment.getFullName())) {
            setCommentStateUnhighlighted(holder, baseNode, false);
        }
        if (deleted.contains(comment.getFullName())) {
            holder.firstTextView.setText(R.string.comment_deleted);
            holder.content.setText(R.string.comment_deleted);
        }
        if (currentlyEditingId.equals(comment.getFullName())) {
            setCommentStateUnhighlighted(holder, baseNode, false);
            setCommentStateHighlighted(holder, comment, baseNode, true, false);
        }
    } else if (firstHolder instanceof SubmissionViewHolder && submission != null) {
        submissionViewHolder = (SubmissionViewHolder) firstHolder;
        new PopulateSubmissionViewHolder().populateSubmissionViewHolder((SubmissionViewHolder) firstHolder, submission, (Activity) mContext, true, true, null, listView, false, false, null, this);
        if (Authentication.isLoggedIn && Authentication.didOnline) {
            if (submission.isArchived() || submission.isLocked()) {
                firstHolder.itemView.findViewById(R.id.reply).setVisibility(View.GONE);
            } else {
                firstHolder.itemView.findViewById(R.id.reply).setOnClickListener(new OnSingleClickListener() {

                    @Override
                    public void onSingleClick(View v) {
                        doReplySubmission(firstHolder);
                    }
                });
                firstHolder.itemView.findViewById(R.id.discard).setOnClickListener(new OnSingleClickListener() {

                    @Override
                    public void onSingleClick(View v) {
                        firstHolder.itemView.findViewById(R.id.innerSend).setVisibility(View.GONE);
                        currentlyEditing = null;
                        editingPosition = -1;
                        if (SettingValues.fastscroll) {
                            mPage.fastScroll.setVisibility(View.VISIBLE);
                        }
                        if (mPage.fab != null)
                            mPage.fab.setVisibility(View.VISIBLE);
                        mPage.overrideFab = false;
                        currentlyEditingId = "";
                        backedText = "";
                        View view = ((Activity) mContext).getCurrentFocus();
                        if (view != null) {
                            InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                        }
                    }
                });
            }
        } else {
            firstHolder.itemView.findViewById(R.id.innerSend).setVisibility(View.GONE);
            firstHolder.itemView.findViewById(R.id.reply).setVisibility(View.GONE);
        }
        firstHolder.itemView.findViewById(R.id.more).setOnClickListener(new OnSingleClickListener() {

            @Override
            public void onSingleClick(View v) {
                firstHolder.itemView.findViewById(R.id.menu).callOnClick();
            }
        });
    } else if (firstHolder instanceof MoreCommentViewHolder) {
        final MoreCommentViewHolder holder = (MoreCommentViewHolder) firstHolder;
        int nextPos = pos - 1;
        nextPos = getRealPosition(nextPos);
        final MoreChildItem baseNode = (MoreChildItem) currentComments.get(nextPos);
        if (baseNode.children.getCount() > 0) {
            try {
                holder.content.setText(mContext.getString(R.string.comment_load_more_string_new, baseNode.children.getLocalizedCount()));
            } catch (Exception e) {
                holder.content.setText(R.string.comment_load_more_number_unknown);
            }
        } else if (!baseNode.children.getChildrenIds().isEmpty()) {
            holder.content.setText(R.string.comment_load_more_number_unknown);
        } else {
            holder.content.setText(R.string.thread_continue);
        }
        int dwidth = (int) ((SettingValues.largeDepth ? 5 : 3) * Resources.getSystem().getDisplayMetrics().density);
        int width = 0;
        for (int i = 1; i < baseNode.comment.getDepth(); i++) {
            width += dwidth;
        }
        final View progress = holder.loading;
        progress.setVisibility(View.GONE);
        final int finalNextPos = nextPos;
        holder.content.setOnClickListener(new OnSingleClickListener() {

            @Override
            public void onSingleClick(View v) {
                if (baseNode.children.getChildrenIds().isEmpty()) {
                    String toGoTo = "https://reddit.com" + submission.getPermalink() + baseNode.comment.getComment().getId() + "?context=0";
                    new OpenRedditLink(mContext, toGoTo, true);
                } else if (progress.getVisibility() == View.GONE) {
                    progress.setVisibility(View.VISIBLE);
                    holder.content.setText(R.string.comment_loading_more);
                    currentLoading = new AsyncLoadMore(getRealPosition(holder.getAdapterPosition() - 2), holder.getAdapterPosition(), holder, finalNextPos, baseNode.comment.getComment().getFullName());
                    currentLoading.execute(baseNode);
                }
            }
        });
        RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();
        params.setMargins(width, 0, 0, 0);
        holder.itemView.setLayoutParams(params);
    }
    if (firstHolder instanceof SpacerViewHolder) {
        // Make a space the size of the toolbar minus 1 so there isn't a gap
        firstHolder.itemView.findViewById(R.id.height).setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, (Constants.SINGLE_HEADER_VIEW_OFFSET - Reddit.dpToPxVertical(1) + mPage.shownHeaders)));
    }
}
Also used : OnSingleClickListener(me.ccrama.redditslide.util.OnSingleClickListener) BaseActivity(me.ccrama.redditslide.Activities.BaseActivity) Activity(android.app.Activity) InputMethodManager(android.view.inputmethod.InputMethodManager) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) PopulateSubmissionViewHolder(me.ccrama.redditslide.SubmissionViews.PopulateSubmissionViewHolder) Comment(net.dean.jraw.models.Comment) Typeface(android.graphics.Typeface) PopulateSubmissionViewHolder(me.ccrama.redditslide.SubmissionViews.PopulateSubmissionViewHolder) CommentNode(net.dean.jraw.models.CommentNode) ImageView(android.widget.ImageView) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) View(android.view.View) TextView(android.widget.TextView) RecyclerView(android.support.v7.widget.RecyclerView) ApiException(net.dean.jraw.ApiException) FontPreferences(me.ccrama.redditslide.Visuals.FontPreferences) RelativeLayout(android.widget.RelativeLayout) RecyclerView(android.support.v7.widget.RecyclerView) File(java.io.File) LinearLayout(android.widget.LinearLayout) OpenRedditLink(me.ccrama.redditslide.OpenRedditLink)

Example 12 with OnSingleClickListener

use of me.ccrama.redditslide.util.OnSingleClickListener in project Slide by ccrama.

the class SubredditView method doSubSidebar.

public void doSubSidebar(final String subOverride) {
    findViewById(R.id.loader).setVisibility(View.VISIBLE);
    invalidateOptionsMenu();
    if (!subOverride.equalsIgnoreCase("all") && !subOverride.equalsIgnoreCase("frontpage") && !subOverride.equalsIgnoreCase("random") && !subOverride.equalsIgnoreCase("popular") && !subOverride.equalsIgnoreCase("myrandom") && !subOverride.equalsIgnoreCase("randnsfw") && !subOverride.equalsIgnoreCase("friends") && !subOverride.equalsIgnoreCase("mod") && !subOverride.contains("+") && !subOverride.contains(".") && !subOverride.contains("/m/")) {
        if (drawerLayout != null) {
            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, GravityCompat.END);
        }
        loaded = true;
        final View dialoglayout = findViewById(R.id.sidebarsub);
        {
            View submit = (dialoglayout.findViewById(R.id.submit));
            if (!Authentication.isLoggedIn || !Authentication.didOnline) {
                submit.setVisibility(View.GONE);
            }
            if (SettingValues.fab && SettingValues.fabType == Constants.FAB_POST) {
                submit.setVisibility(View.GONE);
            }
            submit.setOnClickListener(new OnSingleClickListener() {

                @Override
                public void onSingleClick(View view) {
                    Intent inte = new Intent(SubredditView.this, Submit.class);
                    if (!subOverride.contains("/m/") && canSubmit) {
                        inte.putExtra(Submit.EXTRA_SUBREDDIT, subOverride);
                    }
                    SubredditView.this.startActivity(inte);
                }
            });
        }
        dialoglayout.findViewById(R.id.wiki).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent i = new Intent(SubredditView.this, Wiki.class);
                i.putExtra(Wiki.EXTRA_SUBREDDIT, subOverride);
                startActivity(i);
            }
        });
        dialoglayout.findViewById(R.id.syncflair).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                ImageFlairs.syncFlairs(SubredditView.this, subreddit);
            }
        });
        dialoglayout.findViewById(R.id.submit).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent i = new Intent(SubredditView.this, Submit.class);
                if ((!subOverride.contains("/m/") || !subOverride.contains(".")) && canSubmit) {
                    i.putExtra(Submit.EXTRA_SUBREDDIT, subOverride);
                }
                startActivity(i);
            }
        });
        final TextView sort = (TextView) dialoglayout.findViewById(R.id.sort);
        Sorting sortingis = Sorting.HOT;
        if (SettingValues.hasSort(subreddit)) {
            sortingis = SettingValues.getBaseSubmissionSort(subreddit);
            sort.setText(sortingis.name() + ((sortingis == Sorting.CONTROVERSIAL || sortingis == Sorting.TOP) ? " of " + SettingValues.getBaseTimePeriod(subreddit).name() : ""));
        } else {
            sort.setText("Set default sorting");
        }
        final int sortid = Reddit.getSortingId(sortingis);
        dialoglayout.findViewById(R.id.sorting).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                final DialogInterface.OnClickListener l2 = new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        switch(i) {
                            case 0:
                                sorts = Sorting.HOT;
                                break;
                            case 1:
                                sorts = Sorting.NEW;
                                break;
                            case 2:
                                sorts = Sorting.RISING;
                                break;
                            case 3:
                                sorts = Sorting.TOP;
                                askTimePeriod(sorts, subreddit, dialoglayout);
                                return;
                            case 4:
                                sorts = Sorting.CONTROVERSIAL;
                                askTimePeriod(sorts, subreddit, dialoglayout);
                                return;
                        }
                        SettingValues.setSubSorting(sorts, time, subreddit);
                        Sorting sortingis = SettingValues.getBaseSubmissionSort(subreddit);
                        sort.setText(sortingis.name() + ((sortingis == Sorting.CONTROVERSIAL || sortingis == Sorting.TOP) ? " of " + SettingValues.getBaseTimePeriod(subreddit).name() : ""));
                        reloadSubs();
                    }
                };
                AlertDialogWrapper.Builder builder = new AlertDialogWrapper.Builder(SubredditView.this);
                builder.setTitle(R.string.sorting_choose);
                builder.setSingleChoiceItems(Reddit.getSortingStrings(getBaseContext()), sortid, l2);
                builder.setNegativeButton("Reset default sorting", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SettingValues.prefs.edit().remove("defaultSort" + subreddit.toLowerCase(Locale.ENGLISH)).apply();
                        SettingValues.prefs.edit().remove("defaultTime" + subreddit.toLowerCase(Locale.ENGLISH)).apply();
                        final TextView sort = (TextView) dialoglayout.findViewById(R.id.sort);
                        if (SettingValues.hasSort(subreddit)) {
                            Sorting sortingis = SettingValues.getBaseSubmissionSort(subreddit);
                            sort.setText(sortingis.name() + ((sortingis == Sorting.CONTROVERSIAL || sortingis == Sorting.TOP) ? " of " + SettingValues.getBaseTimePeriod(subreddit).name() : ""));
                        } else {
                            sort.setText("Set default sorting");
                        }
                        reloadSubs();
                    }
                });
                builder.show();
            }
        });
        dialoglayout.findViewById(R.id.theme).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                int style = new ColorPreferences(SubredditView.this).getThemeSubreddit(subOverride);
                final Context contextThemeWrapper = new ContextThemeWrapper(SubredditView.this, style);
                LayoutInflater localInflater = getLayoutInflater().cloneInContext(contextThemeWrapper);
                final View dialoglayout = localInflater.inflate(R.layout.colorsub, null);
                ArrayList<String> arrayList = new ArrayList<>();
                arrayList.add(subOverride);
                SettingsSubAdapter.showSubThemeEditor(arrayList, SubredditView.this, dialoglayout);
            }
        });
        dialoglayout.findViewById(R.id.mods).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                final Dialog d = new MaterialDialog.Builder(SubredditView.this).title(R.string.sidebar_findingmods).cancelable(true).content(R.string.misc_please_wait).progress(true, 100).show();
                new AsyncTask<Void, Void, Void>() {

                    ArrayList<UserRecord> mods;

                    @Override
                    protected Void doInBackground(Void... params) {
                        mods = new ArrayList<>();
                        UserRecordPaginator paginator = new UserRecordPaginator(Authentication.reddit, subOverride, "moderators");
                        paginator.setSorting(Sorting.HOT);
                        paginator.setTimePeriod(TimePeriod.ALL);
                        while (paginator.hasNext()) {
                            mods.addAll(paginator.next());
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void aVoid) {
                        final ArrayList<String> names = new ArrayList<>();
                        for (UserRecord rec : mods) {
                            names.add(rec.getFullName());
                        }
                        d.dismiss();
                        new MaterialDialog.Builder(SubredditView.this).title(getString(R.string.sidebar_submods, subreddit)).items(names).itemsCallback(new MaterialDialog.ListCallback() {

                            @Override
                            public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                Intent i = new Intent(SubredditView.this, Profile.class);
                                i.putExtra(Profile.EXTRA_PROFILE, names.get(which));
                                startActivity(i);
                            }
                        }).positiveText(R.string.btn_message).onPositive(new MaterialDialog.SingleButtonCallback() {

                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                Intent i = new Intent(SubredditView.this, SendMessage.class);
                                i.putExtra(SendMessage.EXTRA_NAME, "/r/" + subOverride);
                                startActivity(i);
                            }
                        }).show();
                    }
                }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            }
        });
        dialoglayout.findViewById(R.id.flair).setVisibility(View.GONE);
        if (Authentication.didOnline && Authentication.isLoggedIn) {
            new AsyncTask<View, Void, View>() {

                List<FlairTemplate> flairs;

                ArrayList<String> flairText;

                String current;

                AccountManager m;

                @Override
                protected View doInBackground(View... params) {
                    try {
                        m = new AccountManager(Authentication.reddit);
                        JsonNode node = m.getFlairChoicesRootNode(subOverride, null);
                        flairs = m.getFlairChoices(subOverride, node);
                        FlairTemplate currentF = m.getCurrentFlair(subOverride, node);
                        if (currentF != null) {
                            if (currentF.getText().isEmpty()) {
                                current = ("[" + currentF.getCssClass() + "]");
                            } else {
                                current = (currentF.getText());
                            }
                        }
                        flairText = new ArrayList<>();
                        for (FlairTemplate temp : flairs) {
                            if (temp.getText().isEmpty()) {
                                flairText.add("[" + temp.getCssClass() + "]");
                            } else {
                                flairText.add(temp.getText());
                            }
                        }
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                    return params[0];
                }

                @Override
                protected void onPostExecute(View flair) {
                    if (flairs != null && !flairs.isEmpty() && flairText != null && !flairText.isEmpty()) {
                        flair.setVisibility(View.VISIBLE);
                        if (current != null) {
                            ((TextView) dialoglayout.findViewById(R.id.flair_text)).setText(getString(R.string.sidebar_flair, current));
                        }
                        flair.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                new MaterialDialog.Builder(SubredditView.this).items(flairText).title(R.string.sidebar_select_flair).itemsCallback(new MaterialDialog.ListCallback() {

                                    @Override
                                    public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                        final FlairTemplate t = flairs.get(which);
                                        if (t.isTextEditable()) {
                                            new MaterialDialog.Builder(SubredditView.this).title(R.string.sidebar_select_flair_text).input(getString(R.string.mod_flair_hint), t.getText(), true, new MaterialDialog.InputCallback() {

                                                @Override
                                                public void onInput(MaterialDialog dialog, CharSequence input) {
                                                }
                                            }).positiveText(R.string.btn_set).onPositive(new MaterialDialog.SingleButtonCallback() {

                                                @Override
                                                public void onClick(MaterialDialog dialog, DialogAction which) {
                                                    final String flair = dialog.getInputEditText().getText().toString();
                                                    new AsyncTask<Void, Void, Boolean>() {

                                                        @Override
                                                        protected Boolean doInBackground(Void... params) {
                                                            try {
                                                                new ModerationManager(Authentication.reddit).setFlair(subOverride, t, flair, Authentication.name);
                                                                FlairTemplate currentF = m.getCurrentFlair(subOverride);
                                                                if (currentF.getText().isEmpty()) {
                                                                    current = ("[" + currentF.getCssClass() + "]");
                                                                } else {
                                                                    current = (currentF.getText());
                                                                }
                                                                return true;
                                                            } catch (Exception e) {
                                                                e.printStackTrace();
                                                                return false;
                                                            }
                                                        }

                                                        @Override
                                                        protected void onPostExecute(Boolean done) {
                                                            Snackbar s;
                                                            if (done) {
                                                                if (current != null) {
                                                                    ((TextView) dialoglayout.findViewById(R.id.flair_text)).setText(getString(R.string.sidebar_flair, current));
                                                                }
                                                                s = Snackbar.make(mToolbar, R.string.snackbar_flair_success, Snackbar.LENGTH_SHORT);
                                                            } else {
                                                                s = Snackbar.make(mToolbar, R.string.snackbar_flair_error, Snackbar.LENGTH_SHORT);
                                                            }
                                                            if (s != null) {
                                                                View view = s.getView();
                                                                TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
                                                                tv.setTextColor(Color.WHITE);
                                                                s.show();
                                                            }
                                                        }
                                                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                                }
                                            }).negativeText(R.string.btn_cancel).show();
                                        } else {
                                            new AsyncTask<Void, Void, Boolean>() {

                                                @Override
                                                protected Boolean doInBackground(Void... params) {
                                                    try {
                                                        new ModerationManager(Authentication.reddit).setFlair(subOverride, t, null, Authentication.name);
                                                        FlairTemplate currentF = m.getCurrentFlair(subOverride);
                                                        if (currentF.getText().isEmpty()) {
                                                            current = ("[" + currentF.getCssClass() + "]");
                                                        } else {
                                                            current = (currentF.getText());
                                                        }
                                                        return true;
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                        return false;
                                                    }
                                                }

                                                @Override
                                                protected void onPostExecute(Boolean done) {
                                                    Snackbar s;
                                                    if (done) {
                                                        if (current != null) {
                                                            ((TextView) dialoglayout.findViewById(R.id.flair_text)).setText(getString(R.string.sidebar_flair, current));
                                                        }
                                                        s = Snackbar.make(mToolbar, R.string.snackbar_flair_success, Snackbar.LENGTH_SHORT);
                                                    } else {
                                                        s = Snackbar.make(mToolbar, R.string.snackbar_flair_error, Snackbar.LENGTH_SHORT);
                                                    }
                                                    if (s != null) {
                                                        View view = s.getView();
                                                        TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
                                                        tv.setTextColor(Color.WHITE);
                                                        s.show();
                                                    }
                                                }
                                            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                        }
                                    }
                                }).show();
                            }
                        });
                    }
                }
            }.execute(dialoglayout.findViewById(R.id.flair));
        }
    } else {
        if (drawerLayout != null) {
            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.END);
        }
    }
}
Also used : UserRecordPaginator(net.dean.jraw.paginators.UserRecordPaginator) DialogInterface(android.content.DialogInterface) OnSingleClickListener(me.ccrama.redditslide.util.OnSingleClickListener) ArrayList(java.util.ArrayList) JsonNode(com.fasterxml.jackson.databind.JsonNode) AlertDialogWrapper(com.afollestad.materialdialogs.AlertDialogWrapper) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Dialog(android.app.Dialog) NonNull(android.support.annotation.NonNull) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) TextView(android.widget.TextView) Context(android.content.Context) ModerationManager(net.dean.jraw.managers.ModerationManager) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) ColorPreferences(me.ccrama.redditslide.ColorPreferences) FlairTemplate(net.dean.jraw.models.FlairTemplate) 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) ActivityNotFoundException(android.content.ActivityNotFoundException) NetworkException(net.dean.jraw.http.NetworkException) Sorting(net.dean.jraw.paginators.Sorting) ContextThemeWrapper(android.support.v7.view.ContextThemeWrapper) UserRecord(net.dean.jraw.models.UserRecord) DialogAction(com.afollestad.materialdialogs.DialogAction) LayoutInflater(android.view.LayoutInflater) AccountManager(net.dean.jraw.managers.AccountManager) Snackbar(android.support.design.widget.Snackbar)

Example 13 with OnSingleClickListener

use of me.ccrama.redditslide.util.OnSingleClickListener in project Slide by ccrama.

the class Settings method setSettingItems.

private void setSettingItems() {
    View pro = findViewById(R.id.pro);
    if (SettingValues.tabletUI) {
        pro.setVisibility(View.GONE);
    } else {
        pro.setOnClickListener(new OnSingleClickListener() {

            @Override
            public void onSingleClick(View v) {
                new AlertDialogWrapper.Builder(Settings.this).setTitle(R.string.settings_support_slide).setMessage(R.string.pro_upgrade_msg).setPositiveButton(R.string.btn_yes_exclaim, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        try {
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=me.ccrama.slideforreddittabletuiunlock")));
                        } catch (ActivityNotFoundException e) {
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=me.ccrama.slideforreddittabletuiunlock")));
                        }
                    }
                }).setNegativeButton(R.string.btn_no_danks, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.dismiss();
                    }
                }).show();
            }
        });
    }
    findViewById(R.id.general).setOnClickListener(new OnSingleClickListener() {

        @Override
        public void onSingleClick(View v) {
            Intent i = new Intent(Settings.this, SettingsGeneral.class);
            startActivityForResult(i, RESTART_SETTINGS_RESULT);
        }
    });
    findViewById(R.id.history).setOnClickListener(new OnSingleClickListener() {

        @Override
        public void onSingleClick(View v) {
            Intent i = new Intent(Settings.this, SettingsHistory.class);
            startActivity(i);
        }
    });
    findViewById(R.id.about).setOnClickListener(new OnSingleClickListener() {

        @Override
        public void onSingleClick(View v) {
            Intent i = new Intent(Settings.this, SettingsAbout.class);
            startActivity(i);
        }
    });
    findViewById(R.id.offline).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent i = new Intent(Settings.this, ManageOfflineContent.class);
            startActivity(i);
        }
    });
    findViewById(R.id.datasave).setOnClickListener(new OnSingleClickListener() {

        @Override
        public void onSingleClick(View v) {
            Intent i = new Intent(Settings.this, SettingsData.class);
            startActivity(i);
        }
    });
    findViewById(R.id.subtheme).setOnClickListener(new OnSingleClickListener() {

        @Override
        public void onSingleClick(View v) {
            Intent i = new Intent(Settings.this, SettingsSubreddit.class);
            startActivityForResult(i, RESTART_SETTINGS_RESULT);
        }
    });
    findViewById(R.id.filter).setOnClickListener(new OnSingleClickListener() {

        @Override
        public void onSingleClick(View v) {
            Intent i = new Intent(Settings.this, SettingsFilter.class);
            startActivity(i);
        }
    });
    findViewById(R.id.synccit).setOnClickListener(new OnSingleClickListener() {

        @Override
        public void onSingleClick(View v) {
            Intent i = new Intent(Settings.this, SettingsSynccit.class);
            startActivity(i);
        }
    });
    findViewById(R.id.reorder).setOnClickListener(new OnSingleClickListener() {

        @Override
        public void onSingleClick(View view) {
            Intent inte = new Intent(Settings.this, ReorderSubreddits.class);
            Settings.this.startActivity(inte);
        }
    });
    findViewById(R.id.theme).setOnClickListener(new OnSingleClickListener() {

        @Override
        public void onSingleClick(View v) {
            Intent i = new Intent(Settings.this, SettingsTheme.class);
            startActivityForResult(i, RESTART_SETTINGS_RESULT);
        }
    });
    findViewById(R.id.handling).setOnClickListener(new OnSingleClickListener() {

        @Override
        public void onSingleClick(View v) {
            Intent i = new Intent(Settings.this, SettingsHandling.class);
            startActivity(i);
        }
    });
    findViewById(R.id.layout).setOnClickListener(new OnSingleClickListener() {

        @Override
        public void onSingleClick(View v) {
            Intent i = new Intent(Settings.this, EditCardsLayout.class);
            startActivity(i);
        }
    });
    findViewById(R.id.backup).setOnClickListener(new OnSingleClickListener() {

        @Override
        public void onSingleClick(View v) {
            Intent i = new Intent(Settings.this, SettingsBackup.class);
            startActivity(i);
        }
    });
    findViewById(R.id.font).setOnClickListener(new OnSingleClickListener() {

        @Override
        public void onSingleClick(View v) {
            Intent i = new Intent(Settings.this, SettingsFont.class);
            startActivity(i);
        }
    });
    findViewById(R.id.tablet).setOnClickListener(new OnSingleClickListener() {

        @Override
        public void onSingleClick(View view) {
            /*  Intent inte = new Intent(Overview.this, Overview.class);
                    inte.putExtra("type", UpdateSubreddits.COLLECTIONS);
                    Overview.this.startActivity(inte);*/
            if (SettingValues.tabletUI) {
                LayoutInflater inflater = getLayoutInflater();
                final View dialoglayout = inflater.inflate(R.layout.tabletui, null);
                final AlertDialogWrapper.Builder builder = new AlertDialogWrapper.Builder(Settings.this);
                final Resources res = getResources();
                dialoglayout.findViewById(R.id.title).setBackgroundColor(Palette.getDefaultColor());
                // todo final Slider portrait = (Slider) dialoglayout.findViewById(R.id.portrait);
                final SeekBar landscape = (SeekBar) dialoglayout.findViewById(R.id.landscape);
                // todo  portrait.setBackgroundColor(Palette.getDefaultColor());
                landscape.setProgress(Reddit.dpWidth - 1);
                ((TextView) dialoglayout.findViewById(R.id.progressnumber)).setText(res.getQuantityString(R.plurals.landscape_columns, landscape.getProgress() + 1, landscape.getProgress() + 1));
                landscape.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        ((TextView) dialoglayout.findViewById(R.id.progressnumber)).setText(res.getQuantityString(R.plurals.landscape_columns, landscape.getProgress() + 1, landscape.getProgress() + 1));
                        Settings.changed = true;
                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {
                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                    }
                });
                final Dialog dialog = builder.setView(dialoglayout).create();
                dialog.show();
                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        Reddit.dpWidth = landscape.getProgress() + 1;
                        Reddit.colors.edit().putInt("tabletOVERRIDE", landscape.getProgress() + 1).apply();
                    }
                });
                SwitchCompat s = (SwitchCompat) dialog.findViewById(R.id.dualcolumns);
                s.setChecked(SettingValues.dualPortrait);
                s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        SettingValues.dualPortrait = isChecked;
                        SettingValues.prefs.edit().putBoolean(SettingValues.PREF_DUAL_PORTRAIT, isChecked).apply();
                    }
                });
                SwitchCompat s2 = (SwitchCompat) dialog.findViewById(R.id.fullcomment);
                s2.setChecked(SettingValues.fullCommentOverride);
                s2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        SettingValues.fullCommentOverride = isChecked;
                        SettingValues.prefs.edit().putBoolean(SettingValues.PREF_FULL_COMMENT_OVERRIDE, isChecked).apply();
                    }
                });
                SwitchCompat s3 = (SwitchCompat) dialog.findViewById(R.id.singlecolumnmultiwindow);
                s3.setChecked(SettingValues.singleColumnMultiWindow);
                s3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        SettingValues.singleColumnMultiWindow = isChecked;
                        SettingValues.prefs.edit().putBoolean(SettingValues.PREF_SINGLE_COLUMN_MULTI, isChecked).apply();
                    }
                });
            } else {
                new AlertDialogWrapper.Builder(Settings.this).setTitle("Mutli-Column Settings are a Pro feature").setMessage(R.string.pro_upgrade_msg).setPositiveButton(R.string.btn_yes_exclaim, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        try {
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=me.ccrama.slideforreddittabletuiunlock")));
                        } catch (android.content.ActivityNotFoundException anfe) {
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=me.ccrama.slideforreddittabletuiunlock")));
                        }
                    }
                }).setNegativeButton(R.string.btn_no_danks, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                }).show();
            }
        }
    });
    if (FDroid.isFDroid) {
        ((TextView) findViewById(R.id.donatetext)).setText("Donate via PayPal");
    }
    findViewById(R.id.support).setOnClickListener(new OnSingleClickListener() {

        @Override
        public void onSingleClick(View v) {
            if (FDroid.isFDroid) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=56FKCCYLX7L72"));
                startActivity(browserIntent);
            } else {
                Intent inte = new Intent(Settings.this, DonateView.class);
                Settings.this.startActivity(inte);
            }
        }
    });
    findViewById(R.id.comments).setOnClickListener(new OnSingleClickListener() {

        @Override
        public void onSingleClick(View v) {
            Intent inte = new Intent(Settings.this, SettingsComments.class);
            Settings.this.startActivity(inte);
        }
    });
    if (Authentication.isLoggedIn && NetworkUtil.isConnected(this)) {
        findViewById(R.id.reddit_settings).setOnClickListener(new OnSingleClickListener() {

            @Override
            public void onSingleClick(View v) {
                Intent i = new Intent(Settings.this, SettingsReddit.class);
                startActivity(i);
            }
        });
    } else {
        findViewById(R.id.reddit_settings).setEnabled(false);
        findViewById(R.id.reddit_settings).setAlpha(0.25f);
    }
}
Also used : ReorderSubreddits(me.ccrama.redditslide.DragSort.ReorderSubreddits) DialogInterface(android.content.DialogInterface) OnSingleClickListener(me.ccrama.redditslide.util.OnSingleClickListener) AlertDialogWrapper(com.afollestad.materialdialogs.AlertDialogWrapper) Dialog(android.app.Dialog) TextView(android.widget.TextView) SeekBar(android.widget.SeekBar) Intent(android.content.Intent) View(android.view.View) TextView(android.widget.TextView) ScrollView(android.widget.ScrollView) ActivityNotFoundException(android.content.ActivityNotFoundException) ActivityNotFoundException(android.content.ActivityNotFoundException) LayoutInflater(android.view.LayoutInflater) Resources(android.content.res.Resources) CompoundButton(android.widget.CompoundButton) SwitchCompat(android.support.v7.widget.SwitchCompat)

Example 14 with OnSingleClickListener

use of me.ccrama.redditslide.util.OnSingleClickListener in project Slide by ccrama.

the class SettingsGeneral method onCreate.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    applyColorTheme();
    setContentView(R.layout.activity_settings_general);
    setupAppBar(R.id.toolbar, R.string.settings_title_general, true, true);
    {
        SwitchCompat single = (SwitchCompat) findViewById(R.id.immersivemode);
        single.setChecked(SettingValues.immersiveMode);
        single.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SettingsTheme.changed = true;
                SettingValues.immersiveMode = isChecked;
                SettingValues.prefs.edit().putBoolean(SettingValues.PREF_IMMERSIVE_MODE, isChecked).apply();
            }
        });
    }
    {
        SwitchCompat single = (SwitchCompat) findViewById(R.id.forcelanguage);
        single.setChecked(SettingValues.overrideLanguage);
        single.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SettingsTheme.changed = true;
                SettingValues.overrideLanguage = isChecked;
                SettingValues.prefs.edit().putBoolean(SettingValues.PREF_OVERRIDE_LANGUAGE, isChecked).apply();
            }
        });
    }
    {
        SwitchCompat single = (SwitchCompat) findViewById(R.id.subfolder);
        single.setChecked(SettingValues.imageSubfolders);
        single.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SettingValues.imageSubfolders = isChecked;
                SettingValues.prefs.edit().putBoolean(SettingValues.PREF_IMAGE_SUBFOLDERS, isChecked).apply();
            }
        });
    }
    {
        findViewById(R.id.download).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                new FolderChooserDialogCreate.Builder(SettingsGeneral.this).chooseButton(// changes label of the choose button
                R.string.btn_select).initialPath(Environment.getExternalStorageDirectory().getPath()).show();
            }
        });
    }
    String loc = Reddit.appRestart.getString("imagelocation", getString(R.string.settings_image_location_unset));
    ((TextView) findViewById(R.id.location)).setText(loc);
    {
        SwitchCompat single = (SwitchCompat) findViewById(R.id.expandedmenu);
        single.setChecked(SettingValues.expandedToolbar);
        single.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SettingValues.expandedToolbar = isChecked;
                SettingValues.prefs.edit().putBoolean(SettingValues.PREF_EXPANDED_TOOLBAR, isChecked).apply();
            }
        });
    }
    findViewById(R.id.viewtype).setOnClickListener(new OnSingleClickListener() {

        @Override
        public void onSingleClick(View v) {
            Intent i = new Intent(SettingsGeneral.this, SettingsViewType.class);
            startActivity(i);
        }
    });
    // FAB multi choice//
    ((TextView) findViewById(R.id.fab_current)).setText(SettingValues.fab ? (SettingValues.fabType == Constants.FAB_DISMISS ? getString(R.string.fab_hide) : getString(R.string.fab_create)) : getString(R.string.fab_disabled));
    findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            PopupMenu popup = new PopupMenu(SettingsGeneral.this, v);
            popup.getMenuInflater().inflate(R.menu.fab_settings, popup.getMenu());
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

                public boolean onMenuItemClick(MenuItem item) {
                    switch(item.getItemId()) {
                        case R.id.disabled:
                            SettingValues.fab = false;
                            SettingValues.prefs.edit().putBoolean(SettingValues.PREF_FAB, false).apply();
                            break;
                        case R.id.hide:
                            SettingValues.fab = true;
                            SettingValues.fabType = Constants.FAB_DISMISS;
                            SettingValues.prefs.edit().putInt(SettingValues.PREF_FAB_TYPE, Constants.FAB_DISMISS).apply();
                            SettingValues.prefs.edit().putBoolean(SettingValues.PREF_FAB, true).apply();
                            break;
                        case R.id.create:
                            SettingValues.fab = true;
                            SettingValues.fabType = Constants.FAB_POST;
                            SettingValues.prefs.edit().putInt(SettingValues.PREF_FAB_TYPE, Constants.FAB_POST).apply();
                            SettingValues.prefs.edit().putBoolean(SettingValues.PREF_FAB, true).apply();
                            break;
                    }
                    ((TextView) findViewById(R.id.fab_current)).setText(SettingValues.fab ? (SettingValues.fabType == Constants.FAB_DISMISS ? getString(R.string.fab_hide) : getString(R.string.fab_create)) : getString(R.string.fab_disabled));
                    return true;
                }
            });
            popup.show();
        }
    });
    // SettingValues.subredditSearchMethod == 1 for drawer, 2 for toolbar, 3 for both
    final TextView currentMethodTitle = (TextView) findViewById(R.id.subreddit_search_method_current);
    if (SettingValues.subredditSearchMethod == Constants.SUBREDDIT_SEARCH_METHOD_DRAWER) {
        currentMethodTitle.setText(getString(R.string.subreddit_search_method_drawer));
    } else if (SettingValues.subredditSearchMethod == Constants.SUBREDDIT_SEARCH_METHOD_TOOLBAR) {
        currentMethodTitle.setText(getString(R.string.subreddit_search_method_toolbar));
    } else if (SettingValues.subredditSearchMethod == Constants.SUBREDDIT_SEARCH_METHOD_BOTH) {
        currentMethodTitle.setText(getString(R.string.subreddit_search_method_both));
    }
    findViewById(R.id.subreddit_search_method).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            PopupMenu popup = new PopupMenu(SettingsGeneral.this, v);
            popup.getMenuInflater().inflate(R.menu.subreddit_search_settings, popup.getMenu());
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

                public boolean onMenuItemClick(MenuItem item) {
                    switch(item.getItemId()) {
                        case R.id.subreddit_search_drawer:
                            SettingValues.subredditSearchMethod = Constants.SUBREDDIT_SEARCH_METHOD_DRAWER;
                            SettingValues.prefs.edit().putInt(SettingValues.PREF_SUBREDDIT_SEARCH_METHOD, Constants.SUBREDDIT_SEARCH_METHOD_DRAWER).apply();
                            SettingsGeneral.searchChanged = true;
                            break;
                        case R.id.subreddit_search_toolbar:
                            SettingValues.subredditSearchMethod = Constants.SUBREDDIT_SEARCH_METHOD_TOOLBAR;
                            SettingValues.prefs.edit().putInt(SettingValues.PREF_SUBREDDIT_SEARCH_METHOD, Constants.SUBREDDIT_SEARCH_METHOD_TOOLBAR).apply();
                            SettingsGeneral.searchChanged = true;
                            break;
                        case R.id.subreddit_search_both:
                            SettingValues.subredditSearchMethod = Constants.SUBREDDIT_SEARCH_METHOD_BOTH;
                            SettingValues.prefs.edit().putInt(SettingValues.PREF_SUBREDDIT_SEARCH_METHOD, Constants.SUBREDDIT_SEARCH_METHOD_BOTH).apply();
                            SettingsGeneral.searchChanged = true;
                            break;
                    }
                    if (SettingValues.subredditSearchMethod == Constants.SUBREDDIT_SEARCH_METHOD_DRAWER) {
                        currentMethodTitle.setText(getString(R.string.subreddit_search_method_drawer));
                    } else if (SettingValues.subredditSearchMethod == Constants.SUBREDDIT_SEARCH_METHOD_TOOLBAR) {
                        currentMethodTitle.setText(getString(R.string.subreddit_search_method_toolbar));
                    } else if (SettingValues.subredditSearchMethod == Constants.SUBREDDIT_SEARCH_METHOD_BOTH) {
                        currentMethodTitle.setText(getString(R.string.subreddit_search_method_both));
                    }
                    return true;
                }
            });
            popup.show();
        }
    });
    {
        SwitchCompat single = (SwitchCompat) findViewById(R.id.exitcheck);
        single.setChecked(SettingValues.exit);
        single.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SettingValues.exit = isChecked;
                SettingValues.prefs.edit().putBoolean(SettingValues.PREF_EXIT, isChecked).apply();
            }
        });
    }
    if (Reddit.notificationTime > 0) {
        ((TextView) findViewById(R.id.notifications_current)).setText(getString(R.string.settings_notification_short, TimeUtils.getTimeInHoursAndMins(Reddit.notificationTime, getBaseContext())));
        setSubText();
    } else {
        ((TextView) findViewById(R.id.notifications_current)).setText(R.string.settings_notifdisabled);
        ((TextView) findViewById(R.id.sub_notifs_current)).setText(R.string.settings_enable_notifs);
    }
    if (Authentication.isLoggedIn) {
        findViewById(R.id.notifications).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                LayoutInflater inflater = getLayoutInflater();
                final View dialoglayout = inflater.inflate(R.layout.inboxfrequency, null);
                setupNotificationSettings(dialoglayout, SettingsGeneral.this);
            }
        });
        findViewById(R.id.sub_notifications).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                showSelectDialog();
            }
        });
    } else {
        findViewById(R.id.notifications).setEnabled(false);
        findViewById(R.id.notifications).setAlpha(0.25f);
        findViewById(R.id.sub_notifications).setEnabled(false);
        findViewById(R.id.sub_notifications).setAlpha(0.25f);
    }
    ((TextView) findViewById(R.id.sorting_current)).setText(Reddit.getSortingStrings(getBaseContext())[Reddit.getSortingId("")]);
    {
        findViewById(R.id.sorting).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                final DialogInterface.OnClickListener l2 = new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        switch(i) {
                            case 0:
                                Reddit.defaultSorting = Sorting.HOT;
                                break;
                            case 1:
                                Reddit.defaultSorting = Sorting.NEW;
                                break;
                            case 2:
                                Reddit.defaultSorting = Sorting.RISING;
                                break;
                            case 3:
                                Reddit.defaultSorting = Sorting.TOP;
                                askTimePeriod();
                                return;
                            case 4:
                                Reddit.defaultSorting = Sorting.CONTROVERSIAL;
                                askTimePeriod();
                                return;
                        }
                        SettingValues.prefs.edit().putString("defaultSorting", Reddit.defaultSorting.name()).apply();
                        SettingValues.defaultSorting = Reddit.defaultSorting;
                        ((TextView) findViewById(R.id.sorting_current)).setText(Reddit.getSortingStrings(getBaseContext())[Reddit.getSortingId("")]);
                    }
                };
                AlertDialogWrapper.Builder builder = new AlertDialogWrapper.Builder(SettingsGeneral.this);
                builder.setTitle(R.string.sorting_choose);
                builder.setSingleChoiceItems(Reddit.getSortingStrings(getBaseContext()), Reddit.getSortingId(""), l2);
                builder.show();
            }
        });
    }
    doNotifText();
    {
        final int i2 = SettingValues.defaultCommentSorting == CommentSort.CONFIDENCE ? 0 : SettingValues.defaultCommentSorting == CommentSort.TOP ? 1 : SettingValues.defaultCommentSorting == CommentSort.NEW ? 2 : SettingValues.defaultCommentSorting == CommentSort.CONTROVERSIAL ? 3 : SettingValues.defaultCommentSorting == CommentSort.OLD ? 4 : SettingValues.defaultCommentSorting == CommentSort.QA ? 5 : 0;
        ((TextView) findViewById(R.id.sorting_current_comment)).setText(Reddit.getSortingStringsComments(getBaseContext())[i2]);
        findViewById(R.id.sorting_comment).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                final DialogInterface.OnClickListener l2 = new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        CommentSort commentSorting = SettingValues.defaultCommentSorting;
                        switch(i) {
                            case 0:
                                commentSorting = CommentSort.CONFIDENCE;
                                break;
                            case 1:
                                commentSorting = CommentSort.TOP;
                                break;
                            case 2:
                                commentSorting = CommentSort.NEW;
                                break;
                            case 3:
                                commentSorting = CommentSort.CONTROVERSIAL;
                                break;
                            case 4:
                                commentSorting = CommentSort.OLD;
                                break;
                            case 5:
                                commentSorting = CommentSort.QA;
                                break;
                        }
                        SettingValues.prefs.edit().putString("defaultCommentSortingNew", commentSorting.name()).apply();
                        SettingValues.defaultCommentSorting = commentSorting;
                        ((TextView) findViewById(R.id.sorting_current_comment)).setText(Reddit.getSortingStringsComments(getBaseContext())[i]);
                    }
                };
                AlertDialogWrapper.Builder builder = new AlertDialogWrapper.Builder(SettingsGeneral.this);
                builder.setTitle(R.string.sorting_choose);
                Resources res = getBaseContext().getResources();
                builder.setSingleChoiceItems(new String[] { res.getString(R.string.sorting_best), res.getString(R.string.sorting_top), res.getString(R.string.sorting_new), res.getString(R.string.sorting_controversial), res.getString(R.string.sorting_old), res.getString(R.string.sorting_ama) }, i2, l2);
                builder.show();
            }
        });
    }
}
Also used : DialogInterface(android.content.DialogInterface) OnSingleClickListener(me.ccrama.redditslide.util.OnSingleClickListener) AlertDialogWrapper(com.afollestad.materialdialogs.AlertDialogWrapper) TextView(android.widget.TextView) Intent(android.content.Intent) MenuItem(android.view.MenuItem) View(android.view.View) TextView(android.widget.TextView) FolderChooserDialogCreate(me.ccrama.redditslide.Fragments.FolderChooserDialogCreate) LayoutInflater(android.view.LayoutInflater) CommentSort(net.dean.jraw.models.CommentSort) Resources(android.content.res.Resources) CompoundButton(android.widget.CompoundButton) SwitchCompat(android.support.v7.widget.SwitchCompat) PopupMenu(android.support.v7.widget.PopupMenu)

Example 15 with OnSingleClickListener

use of me.ccrama.redditslide.util.OnSingleClickListener in project Slide by ccrama.

the class PopulateSubmissionViewHolder method populateSubmissionViewHolder.

public <T extends Contribution> void populateSubmissionViewHolder(final SubmissionViewHolder holder, final Submission submission, final Activity mContext, boolean fullscreen, final boolean full, final List<T> posts, final RecyclerView recyclerview, final boolean same, final boolean offline, final String baseSub, @Nullable final CommentAdapter adapter) {
    holder.itemView.findViewById(R.id.vote).setVisibility(View.GONE);
    if (!offline && UserSubscriptions.modOf != null && submission.getSubredditName() != null && UserSubscriptions.modOf.contains(submission.getSubredditName().toLowerCase(Locale.ENGLISH))) {
        holder.mod.setVisibility(View.VISIBLE);
        final Map<String, Integer> reports = submission.getUserReports();
        final Map<String, String> reports2 = submission.getModeratorReports();
        if (reports.size() + reports2.size() > 0) {
            ((ImageView) holder.mod).setColorFilter(ContextCompat.getColor(mContext, R.color.md_red_300), PorterDuff.Mode.SRC_ATOP);
        } else {
            ((ImageView) holder.mod).setColorFilter((((holder.itemView.getTag(holder.itemView.getId())) != null && holder.itemView.getTag(holder.itemView.getId()).equals("none") || full)) ? getCurrentTintColor(mContext) : getWhiteTintColor(), PorterDuff.Mode.SRC_ATOP);
        }
        holder.mod.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                showModBottomSheet(mContext, submission, posts, holder, recyclerview, reports, reports2);
            }
        });
    } else {
        holder.mod.setVisibility(View.GONE);
    }
    holder.menu.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            showBottomSheet(mContext, submission, holder, posts, baseSub, recyclerview, full);
        }
    });
    // Use this to offset the submission score
    int submissionScore = submission.getScore();
    final int commentCount = submission.getCommentCount();
    final int more = LastComments.commentsSince(submission);
    holder.comments.setText(String.format(Locale.getDefault(), "%d %s", commentCount, ((more > 0 && SettingValues.commentLastVisit) ? "(+" + more + ")" : "")));
    String scoreRatio = (SettingValues.upvotePercentage && full && submission.getUpvoteRatio() != null) ? "(" + (int) (submission.getUpvoteRatio() * 100) + "%)" : "";
    if (!scoreRatio.isEmpty()) {
        TextView percent = holder.itemView.findViewById(R.id.percent);
        percent.setVisibility(View.VISIBLE);
        percent.setText(scoreRatio);
        final double numb = (submission.getUpvoteRatio());
        if (numb <= .5) {
            if (numb <= .1) {
                percent.setTextColor(ContextCompat.getColor(mContext, R.color.md_blue_500));
            } else if (numb <= .3) {
                percent.setTextColor(ContextCompat.getColor(mContext, R.color.md_blue_400));
            } else {
                percent.setTextColor(ContextCompat.getColor(mContext, R.color.md_blue_300));
            }
        } else {
            if (numb >= .9) {
                percent.setTextColor(ContextCompat.getColor(mContext, R.color.md_orange_500));
            } else if (numb >= .7) {
                percent.setTextColor(ContextCompat.getColor(mContext, R.color.md_orange_400));
            } else {
                percent.setTextColor(ContextCompat.getColor(mContext, R.color.md_orange_300));
            }
        }
    }
    final ImageView downvotebutton = (ImageView) holder.downvote;
    final ImageView upvotebutton = (ImageView) holder.upvote;
    if (submission.isArchived()) {
        downvotebutton.setVisibility(View.GONE);
        upvotebutton.setVisibility(View.GONE);
    } else if (Authentication.isLoggedIn && Authentication.didOnline) {
        if (SettingValues.actionbarVisible && downvotebutton.getVisibility() != View.VISIBLE) {
            downvotebutton.setVisibility(View.VISIBLE);
            upvotebutton.setVisibility(View.VISIBLE);
        }
    }
    // Set the colors and styles for the score text depending on what state it is in
    switch(ActionStates.getVoteDirection(submission)) {
        case UPVOTE:
            {
                holder.score.setTextColor(ContextCompat.getColor(mContext, R.color.md_orange_500));
                upvotebutton.setColorFilter(ContextCompat.getColor(mContext, R.color.md_orange_500), PorterDuff.Mode.SRC_ATOP);
                holder.score.setTypeface(null, Typeface.BOLD);
                downvotebutton.setColorFilter((((holder.itemView.getTag(holder.itemView.getId())) != null && holder.itemView.getTag(holder.itemView.getId()).equals("none") || full)) ? getCurrentTintColor(mContext) : getWhiteTintColor(), PorterDuff.Mode.SRC_ATOP);
                if (submission.getVote() != VoteDirection.UPVOTE) {
                    if (submission.getVote() == VoteDirection.DOWNVOTE)
                        ++submissionScore;
                    // offset the score by +1
                    ++submissionScore;
                }
                break;
            }
        case DOWNVOTE:
            {
                holder.score.setTextColor(ContextCompat.getColor(mContext, R.color.md_blue_500));
                downvotebutton.setColorFilter(ContextCompat.getColor(mContext, R.color.md_blue_500), PorterDuff.Mode.SRC_ATOP);
                holder.score.setTypeface(null, Typeface.BOLD);
                upvotebutton.setColorFilter((((holder.itemView.getTag(holder.itemView.getId())) != null && holder.itemView.getTag(holder.itemView.getId()).equals("none") || full)) ? getCurrentTintColor(mContext) : getWhiteTintColor(), PorterDuff.Mode.SRC_ATOP);
                if (submission.getVote() != VoteDirection.DOWNVOTE) {
                    if (submission.getVote() == VoteDirection.UPVOTE)
                        --submissionScore;
                    // offset the score by +1
                    --submissionScore;
                }
                break;
            }
        case NO_VOTE:
            {
                holder.score.setTextColor(holder.comments.getCurrentTextColor());
                holder.score.setTypeface(null, Typeface.NORMAL);
                downvotebutton.setColorFilter((((holder.itemView.getTag(holder.itemView.getId())) != null && holder.itemView.getTag(holder.itemView.getId()).equals("none") || full)) ? getCurrentTintColor(mContext) : getWhiteTintColor(), PorterDuff.Mode.SRC_ATOP);
                upvotebutton.setColorFilter((((holder.itemView.getTag(holder.itemView.getId())) != null && holder.itemView.getTag(holder.itemView.getId()).equals("none") || full)) ? getCurrentTintColor(mContext) : getWhiteTintColor(), PorterDuff.Mode.SRC_ATOP);
                break;
            }
    }
    // if the submission is already at 0pts, keep it at 0pts
    submissionScore = ((submissionScore < 0) ? 0 : submissionScore);
    if (submissionScore >= 10000 && SettingValues.abbreviateScores) {
        holder.score.setText(String.format(Locale.getDefault(), "%.1fk", (((double) submissionScore) / 1000)));
    } else {
        holder.score.setText(String.format(Locale.getDefault(), "%d", submissionScore));
    }
    // Save the score so we can use it in the OnClickListeners for the vote buttons
    final int SUBMISSION_SCORE = submissionScore;
    final ImageView hideButton = (ImageView) holder.hide;
    if (hideButton != null) {
        if (SettingValues.hideButton && Authentication.isLoggedIn) {
            hideButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    hideSubmission(submission, posts, baseSub, recyclerview, mContext);
                }
            });
        } else {
            hideButton.setVisibility(View.GONE);
        }
    }
    if (Authentication.isLoggedIn && Authentication.didOnline) {
        if (ActionStates.isSaved(submission)) {
            ((ImageView) holder.save).setColorFilter(ContextCompat.getColor(mContext, R.color.md_amber_500), PorterDuff.Mode.SRC_ATOP);
        } else {
            ((ImageView) holder.save).setColorFilter((((holder.itemView.getTag(holder.itemView.getId())) != null && holder.itemView.getTag(holder.itemView.getId()).equals("none") || full)) ? getCurrentTintColor(mContext) : getWhiteTintColor(), PorterDuff.Mode.SRC_ATOP);
        }
        holder.save.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                saveSubmission(submission, mContext, holder, full);
            }
        });
    }
    if (!SettingValues.saveButton && !full || !Authentication.isLoggedIn || !Authentication.didOnline) {
        holder.save.setVisibility(View.GONE);
    }
    ImageView thumbImage2 = ((ImageView) holder.thumbimage);
    if (holder.leadImage.thumbImage2 == null) {
        holder.leadImage.setThumbnail(thumbImage2);
    }
    final ContentType.Type type = ContentType.getContentType(submission);
    addClickFunctions(holder.leadImage, type, mContext, submission, holder, full);
    if (thumbImage2 != null) {
        addClickFunctions(thumbImage2, type, mContext, submission, holder, full);
    }
    if (full) {
        addClickFunctions(holder.itemView.findViewById(R.id.wraparea), type, mContext, submission, holder, full);
    }
    if (full) {
        holder.leadImage.setWrapArea(holder.itemView.findViewById(R.id.wraparea));
    }
    boolean crosspost = submission.getDataNode().has("crosspost_parent_list");
    if (full && crosspost) {
        holder.itemView.findViewById(R.id.crosspost).setVisibility(View.VISIBLE);
        ((TextView) holder.itemView.findViewById(R.id.crossinfo)).setText(SubmissionCache.getCrosspostLine(submission, mContext));
        ((Reddit) mContext.getApplicationContext()).getImageLoader().displayImage(submission.getDataNode().get("crosspost_parent_list").get(0).get("thumbnail").asText(), ((ImageView) holder.itemView.findViewById(R.id.crossthumb)));
        holder.itemView.findViewById(R.id.crosspost).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                OpenRedditLink.openUrl(mContext, submission.getDataNode().get("crosspost_parent_list").get(0).get("permalink").asText(), true);
            }
        });
    }
    holder.leadImage.setSubmission(submission, full, baseSub, type);
    holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            if (offline) {
                Snackbar s = Snackbar.make(holder.itemView, mContext.getString(R.string.offline_msg), Snackbar.LENGTH_SHORT);
                View view = s.getView();
                TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                tv.setTextColor(Color.WHITE);
                s.show();
            } else {
                if (SettingValues.actionbarTap && !full) {
                    CreateCardView.toggleActionbar(holder.itemView);
                } else {
                    holder.itemView.findViewById(R.id.menu).callOnClick();
                }
            }
            return true;
        }
    });
    doText(holder, submission, mContext, baseSub, full);
    if (!full && SettingValues.isSelftextEnabled(baseSub) && submission.isSelfPost() && !submission.getSelftext().isEmpty() && !submission.isNsfw() && !submission.getDataNode().get("spoiler").asBoolean() && !submission.getDataNode().get("selftext_html").asText().trim().isEmpty()) {
        holder.body.setVisibility(View.VISIBLE);
        String text = submission.getDataNode().get("selftext_html").asText();
        int typef = new FontPreferences(mContext).getFontTypeComment().getTypeface();
        Typeface typeface;
        if (typef >= 0) {
            typeface = RobotoTypefaces.obtainTypeface(mContext, typef);
        } else {
            typeface = Typeface.DEFAULT;
        }
        holder.body.setTypeface(typeface);
        holder.body.setTextHtml(Html.fromHtml(text.substring(0, text.contains("\n") ? text.indexOf("\n") : text.length())).toString().replace("<sup>", "<sup><small>").replace("</sup>", "</small></sup>"), "none ");
        holder.body.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                holder.itemView.callOnClick();
            }
        });
        holder.body.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                holder.menu.callOnClick();
                return true;
            }
        });
    } else if (!full) {
        holder.body.setVisibility(View.GONE);
    }
    if (full) {
        if (!submission.getSelftext().isEmpty()) {
            int typef = new FontPreferences(mContext).getFontTypeComment().getTypeface();
            Typeface typeface;
            if (typef >= 0) {
                typeface = RobotoTypefaces.obtainTypeface(mContext, typef);
            } else {
                typeface = Typeface.DEFAULT;
            }
            holder.firstTextView.setTypeface(typeface);
            setViews(submission.getDataNode().get("selftext_html").asText(), submission.getSubredditName() == null ? "all" : submission.getSubredditName(), holder);
            holder.itemView.findViewById(R.id.body_area).setVisibility(View.VISIBLE);
        } else {
            holder.itemView.findViewById(R.id.body_area).setVisibility(View.GONE);
        }
    }
    try {
        final TextView points = holder.score;
        final TextView comments = holder.comments;
        if (Authentication.isLoggedIn && !offline && Authentication.didOnline) {
            {
                downvotebutton.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        if (SettingValues.storeHistory && !full) {
                            if (!submission.isNsfw() || SettingValues.storeNSFWHistory) {
                                HasSeen.addSeen(submission.getFullName());
                                if (mContext instanceof MainActivity) {
                                    holder.title.setAlpha(0.54f);
                                    holder.body.setAlpha(0.54f);
                                }
                            }
                        }
                        if (ActionStates.getVoteDirection(submission) != VoteDirection.DOWNVOTE) {
                            // has not been downvoted
                            points.setTextColor(ContextCompat.getColor(mContext, R.color.md_blue_500));
                            downvotebutton.setColorFilter(ContextCompat.getColor(mContext, R.color.md_blue_500), PorterDuff.Mode.SRC_ATOP);
                            upvotebutton.setColorFilter((((holder.itemView.getTag(holder.itemView.getId())) != null && holder.itemView.getTag(holder.itemView.getId()).equals("none") || full)) ? getCurrentTintColor(mContext) : getWhiteTintColor(), PorterDuff.Mode.SRC_ATOP);
                            AnimateHelper.setFlashAnimation(holder.itemView, downvotebutton, ContextCompat.getColor(mContext, R.color.md_blue_500));
                            holder.score.setTypeface(null, Typeface.BOLD);
                            final int DOWNVOTE_SCORE = (SUBMISSION_SCORE == 0) ? 0 : SUBMISSION_SCORE - // if a post is at 0 votes, keep it at 0 when downvoting
                            1;
                            new Vote(false, points, mContext).execute(submission);
                            ActionStates.setVoteDirection(submission, VoteDirection.DOWNVOTE);
                            setSubmissionScoreText(submission, holder);
                        } else {
                            // un-downvoted a post
                            points.setTextColor(comments.getCurrentTextColor());
                            new Vote(points, mContext).execute(submission);
                            holder.score.setTypeface(null, Typeface.NORMAL);
                            ActionStates.setVoteDirection(submission, VoteDirection.NO_VOTE);
                            downvotebutton.setColorFilter((((holder.itemView.getTag(holder.itemView.getId())) != null && holder.itemView.getTag(holder.itemView.getId()).equals("none") || full)) ? getCurrentTintColor(mContext) : getWhiteTintColor(), PorterDuff.Mode.SRC_ATOP);
                            setSubmissionScoreText(submission, holder);
                        }
                        if (!full && !SettingValues.actionbarVisible && SettingValues.defaultCardView != CreateCardView.CardEnum.DESKTOP) {
                            CreateCardView.toggleActionbar(holder.itemView);
                        }
                    }
                });
            }
            {
                upvotebutton.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        if (SettingValues.storeHistory && !full) {
                            if (!submission.isNsfw() || SettingValues.storeNSFWHistory) {
                                HasSeen.addSeen(submission.getFullName());
                                if (mContext instanceof MainActivity) {
                                    holder.title.setAlpha(0.54f);
                                    holder.body.setAlpha(0.54f);
                                }
                            }
                        }
                        if (ActionStates.getVoteDirection(submission) != VoteDirection.UPVOTE) {
                            // has not been upvoted
                            points.setTextColor(ContextCompat.getColor(mContext, R.color.md_orange_500));
                            upvotebutton.setColorFilter(ContextCompat.getColor(mContext, R.color.md_orange_500), PorterDuff.Mode.SRC_ATOP);
                            downvotebutton.setColorFilter((((holder.itemView.getTag(holder.itemView.getId())) != null && holder.itemView.getTag(holder.itemView.getId()).equals("none") || full)) ? getCurrentTintColor(mContext) : getWhiteTintColor(), PorterDuff.Mode.SRC_ATOP);
                            AnimateHelper.setFlashAnimation(holder.itemView, upvotebutton, ContextCompat.getColor(mContext, R.color.md_orange_500));
                            holder.score.setTypeface(null, Typeface.BOLD);
                            new Vote(true, points, mContext).execute(submission);
                            ActionStates.setVoteDirection(submission, VoteDirection.UPVOTE);
                            setSubmissionScoreText(submission, holder);
                        } else {
                            // un-upvoted a post
                            points.setTextColor(comments.getCurrentTextColor());
                            new Vote(points, mContext).execute(submission);
                            holder.score.setTypeface(null, Typeface.NORMAL);
                            ActionStates.setVoteDirection(submission, VoteDirection.NO_VOTE);
                            upvotebutton.setColorFilter((((holder.itemView.getTag(holder.itemView.getId())) != null && holder.itemView.getTag(holder.itemView.getId()).equals("none") || full)) ? getCurrentTintColor(mContext) : getWhiteTintColor(), PorterDuff.Mode.SRC_ATOP);
                            setSubmissionScoreText(submission, holder);
                        }
                        if (!full && !SettingValues.actionbarVisible && SettingValues.defaultCardView != CreateCardView.CardEnum.DESKTOP) {
                            CreateCardView.toggleActionbar(holder.itemView);
                        }
                    }
                });
            }
        } else {
            upvotebutton.setVisibility(View.GONE);
            downvotebutton.setVisibility(View.GONE);
        }
    } catch (Exception ignored) {
        ignored.printStackTrace();
    }
    final View edit = holder.edit;
    if (Authentication.name != null && Authentication.name.toLowerCase(Locale.ENGLISH).equals(submission.getAuthor().toLowerCase(Locale.ENGLISH)) && Authentication.didOnline) {
        edit.setVisibility(View.VISIBLE);
        edit.setOnClickListener(new OnSingleClickListener() {

            @Override
            public void onSingleClick(View v) {
                new AsyncTask<Void, Void, ArrayList<String>>() {

                    List<FlairTemplate> flairlist;

                    @Override
                    protected ArrayList<String> doInBackground(Void... params) {
                        FlairReference allFlairs = new FluentRedditClient(Authentication.reddit).subreddit(submission.getSubredditName()).flair();
                        try {
                            flairlist = allFlairs.options(submission);
                            final ArrayList<String> finalFlairs = new ArrayList<>();
                            for (FlairTemplate temp : flairlist) {
                                finalFlairs.add(temp.getText());
                            }
                            return finalFlairs;
                        } catch (Exception e) {
                            e.printStackTrace();
                        // sub probably has no flairs?
                        }
                        return null;
                    }

                    @Override
                    public void onPostExecute(final ArrayList<String> data) {
                        final boolean flair = (data != null && !data.isEmpty());
                        int[] attrs = new int[] { R.attr.tintColor };
                        TypedArray ta = mContext.obtainStyledAttributes(attrs);
                        final int color2 = ta.getColor(0, Color.WHITE);
                        Drawable edit_drawable = mContext.getResources().getDrawable(R.drawable.edit);
                        Drawable nsfw_drawable = mContext.getResources().getDrawable(R.drawable.hide);
                        Drawable delete_drawable = mContext.getResources().getDrawable(R.drawable.delete);
                        Drawable flair_drawable = mContext.getResources().getDrawable(R.drawable.fontsizedarker);
                        edit_drawable.setColorFilter(color2, PorterDuff.Mode.SRC_ATOP);
                        nsfw_drawable.setColorFilter(color2, PorterDuff.Mode.SRC_ATOP);
                        delete_drawable.setColorFilter(color2, PorterDuff.Mode.SRC_ATOP);
                        flair_drawable.setColorFilter(color2, PorterDuff.Mode.SRC_ATOP);
                        ta.recycle();
                        BottomSheet.Builder b = new BottomSheet.Builder(mContext).title(Html.fromHtml(submission.getTitle()));
                        if (submission.isSelfPost()) {
                            b.sheet(1, edit_drawable, mContext.getString(R.string.edit_selftext));
                        }
                        if (submission.isNsfw()) {
                            b.sheet(4, nsfw_drawable, mContext.getString(R.string.mod_btn_unmark_nsfw));
                        } else {
                            b.sheet(4, nsfw_drawable, mContext.getString(R.string.mod_btn_mark_nsfw));
                        }
                        b.sheet(2, delete_drawable, mContext.getString(R.string.delete_submission));
                        if (flair) {
                            b.sheet(3, flair_drawable, mContext.getString(R.string.set_submission_flair));
                        }
                        b.listener(new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch(which) {
                                    case 1:
                                        {
                                            LayoutInflater inflater = mContext.getLayoutInflater();
                                            final View dialoglayout = inflater.inflate(R.layout.edit_comment, null);
                                            final AlertDialogWrapper.Builder builder = new AlertDialogWrapper.Builder(mContext);
                                            final EditText e = dialoglayout.findViewById(R.id.entry);
                                            e.setText(StringEscapeUtils.unescapeHtml4(submission.getSelftext()));
                                            DoEditorActions.doActions(e, dialoglayout, ((AppCompatActivity) mContext).getSupportFragmentManager(), mContext, null, null);
                                            builder.setCancelable(false).setView(dialoglayout);
                                            final Dialog d = builder.create();
                                            d.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                                            d.show();
                                            dialoglayout.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {

                                                @Override
                                                public void onClick(View v) {
                                                    d.dismiss();
                                                }
                                            });
                                            dialoglayout.findViewById(R.id.submit).setOnClickListener(new View.OnClickListener() {

                                                @Override
                                                public void onClick(View v) {
                                                    final String text = e.getText().toString();
                                                    new AsyncTask<Void, Void, Void>() {

                                                        @Override
                                                        protected Void doInBackground(Void... params) {
                                                            try {
                                                                new AccountManager(Authentication.reddit).updateContribution(submission, text);
                                                                if (adapter != null) {
                                                                    adapter.dataSet.reloadSubmission(adapter);
                                                                }
                                                                d.dismiss();
                                                            } catch (Exception e) {
                                                                (mContext).runOnUiThread(new Runnable() {

                                                                    @Override
                                                                    public void run() {
                                                                        new AlertDialogWrapper.Builder(mContext).setTitle(R.string.comment_delete_err).setMessage(R.string.comment_delete_err_msg).setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {

                                                                            @Override
                                                                            public void onClick(DialogInterface dialog, int which) {
                                                                                dialog.dismiss();
                                                                                doInBackground();
                                                                            }
                                                                        }).setNegativeButton(R.string.btn_no, new DialogInterface.OnClickListener() {

                                                                            @Override
                                                                            public void onClick(DialogInterface dialog, int which) {
                                                                                dialog.dismiss();
                                                                            }
                                                                        }).show();
                                                                    }
                                                                });
                                                            }
                                                            return null;
                                                        }

                                                        @Override
                                                        protected void onPostExecute(Void aVoid) {
                                                            if (adapter != null) {
                                                                adapter.notifyItemChanged(1);
                                                            }
                                                        }
                                                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                                }
                                            });
                                        }
                                        break;
                                    case 2:
                                        {
                                            new AlertDialogWrapper.Builder(mContext).setTitle(R.string.really_delete_submission).setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    new AsyncTask<Void, Void, Void>() {

                                                        @Override
                                                        protected Void doInBackground(Void... params) {
                                                            try {
                                                                new ModerationManager(Authentication.reddit).delete(submission);
                                                            } catch (ApiException e) {
                                                                e.printStackTrace();
                                                            }
                                                            return null;
                                                        }

                                                        @Override
                                                        protected void onPostExecute(Void aVoid) {
                                                            (mContext).runOnUiThread(new Runnable() {

                                                                @Override
                                                                public void run() {
                                                                    (holder.title).setTextHtml(mContext.getString(R.string.content_deleted));
                                                                    if (holder.firstTextView != null) {
                                                                        holder.firstTextView.setText(R.string.content_deleted);
                                                                        holder.commentOverflow.setVisibility(View.GONE);
                                                                    } else {
                                                                        if (holder.itemView.findViewById(R.id.body) != null) {
                                                                            ((TextView) holder.itemView.findViewById(R.id.body)).setText(R.string.content_deleted);
                                                                        }
                                                                    }
                                                                }
                                                            });
                                                        }
                                                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                                }
                                            }).setNegativeButton(R.string.btn_cancel, null).show();
                                        }
                                        break;
                                    case 3:
                                        {
                                            new MaterialDialog.Builder(mContext).items(data).title(R.string.sidebar_select_flair).itemsCallback(new MaterialDialog.ListCallback() {

                                                @Override
                                                public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                                    final FlairTemplate t = flairlist.get(which);
                                                    if (t.isTextEditable()) {
                                                        new MaterialDialog.Builder(mContext).title(R.string.mod_btn_submission_flair_text).input(mContext.getString(R.string.mod_flair_hint), t.getText(), true, new MaterialDialog.InputCallback() {

                                                            @Override
                                                            public void onInput(MaterialDialog dialog, CharSequence input) {
                                                            }
                                                        }).positiveText(R.string.btn_set).onPositive(new MaterialDialog.SingleButtonCallback() {

                                                            @Override
                                                            public void onClick(MaterialDialog dialog, DialogAction which) {
                                                                final String flair = dialog.getInputEditText().getText().toString();
                                                                new AsyncTask<Void, Void, Boolean>() {

                                                                    @Override
                                                                    protected Boolean doInBackground(Void... params) {
                                                                        try {
                                                                            new ModerationManager(Authentication.reddit).setFlair(submission.getSubredditName(), t, flair, submission);
                                                                            return true;
                                                                        } catch (ApiException e) {
                                                                            e.printStackTrace();
                                                                            return false;
                                                                        }
                                                                    }

                                                                    @Override
                                                                    protected void onPostExecute(Boolean done) {
                                                                        Snackbar s = null;
                                                                        if (done) {
                                                                            if (holder.itemView != null) {
                                                                                s = Snackbar.make(holder.itemView, R.string.snackbar_flair_success, Snackbar.LENGTH_SHORT);
                                                                                SubmissionCache.updateTitleFlair(submission, flair, mContext);
                                                                                holder.title.setText(SubmissionCache.getTitleLine(submission, mContext));
                                                                            }
                                                                        } else {
                                                                            if (holder.itemView != null) {
                                                                                s = Snackbar.make(holder.itemView, R.string.snackbar_flair_error, Snackbar.LENGTH_SHORT);
                                                                            }
                                                                        }
                                                                        if (s != null) {
                                                                            View view = s.getView();
                                                                            TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                                                                            tv.setTextColor(Color.WHITE);
                                                                            s.show();
                                                                        }
                                                                    }
                                                                }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                                            }
                                                        }).negativeText(R.string.btn_cancel).show();
                                                    } else {
                                                        new AsyncTask<Void, Void, Boolean>() {

                                                            @Override
                                                            protected Boolean doInBackground(Void... params) {
                                                                try {
                                                                    new ModerationManager(Authentication.reddit).setFlair(submission.getSubredditName(), t, null, submission);
                                                                    return true;
                                                                } catch (ApiException e) {
                                                                    e.printStackTrace();
                                                                    return false;
                                                                }
                                                            }

                                                            @Override
                                                            protected void onPostExecute(Boolean done) {
                                                                Snackbar s = null;
                                                                if (done) {
                                                                    if (holder.itemView != null) {
                                                                        s = Snackbar.make(holder.itemView, R.string.snackbar_flair_success, Snackbar.LENGTH_SHORT);
                                                                        SubmissionCache.updateTitleFlair(submission, t.getCssClass(), mContext);
                                                                        holder.title.setText(SubmissionCache.getTitleLine(submission, mContext));
                                                                    }
                                                                } else {
                                                                    if (holder.itemView != null) {
                                                                        s = Snackbar.make(holder.itemView, R.string.snackbar_flair_error, Snackbar.LENGTH_SHORT);
                                                                    }
                                                                }
                                                                if (s != null) {
                                                                    View view = s.getView();
                                                                    TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                                                                    tv.setTextColor(Color.WHITE);
                                                                    s.show();
                                                                }
                                                            }
                                                        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                                    }
                                                }
                                            }).show();
                                        }
                                        break;
                                    case 4:
                                        if (submission.isNsfw()) {
                                            unNsfwSubmission(mContext, submission, holder);
                                        } else {
                                            setPostNsfw(mContext, submission, holder);
                                        }
                                        break;
                                }
                            }
                        }).show();
                    }
                }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            }
        });
    } else {
        edit.setVisibility(View.GONE);
    }
    if (HasSeen.getSeen(submission) && !full) {
        holder.title.setAlpha(0.54f);
        holder.body.setAlpha(0.54f);
    } else {
        holder.title.setAlpha(1f);
        if (!full) {
            holder.body.setAlpha(1f);
        }
    }
}
Also used : FluentRedditClient(net.dean.jraw.fluent.FluentRedditClient) ContentType(me.ccrama.redditslide.ContentType) SpannableStringBuilder(android.text.SpannableStringBuilder) ArrayList(java.util.ArrayList) FlairReference(net.dean.jraw.fluent.FlairReference) AlertDialogWrapper(com.afollestad.materialdialogs.AlertDialogWrapper) Dialog(android.app.Dialog) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) TypedArray(android.content.res.TypedArray) TextView(android.widget.TextView) ArrayList(java.util.ArrayList) List(java.util.List) ImageView(android.widget.ImageView) EditText(android.widget.EditText) Vote(me.ccrama.redditslide.Vote) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Typeface(android.graphics.Typeface) FlairTemplate(net.dean.jraw.models.FlairTemplate) AsyncTask(android.os.AsyncTask) Drawable(android.graphics.drawable.Drawable) DialogAction(com.afollestad.materialdialogs.DialogAction) LayoutInflater(android.view.LayoutInflater) AccountManager(net.dean.jraw.managers.AccountManager) BottomSheet(com.cocosw.bottomsheet.BottomSheet) Snackbar(android.support.design.widget.Snackbar) DialogInterface(android.content.DialogInterface) OnSingleClickListener(me.ccrama.redditslide.util.OnSingleClickListener) MainActivity(me.ccrama.redditslide.Activities.MainActivity) ModerationManager(net.dean.jraw.managers.ModerationManager) AppCompatActivity(android.support.v7.app.AppCompatActivity) MediaView(me.ccrama.redditslide.Activities.MediaView) ImageView(android.widget.ImageView) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) RecyclerView(android.support.v7.widget.RecyclerView) CreateCardView(me.ccrama.redditslide.Views.CreateCardView) View(android.view.View) TextView(android.widget.TextView) SubredditView(me.ccrama.redditslide.Activities.SubredditView) InvalidScopeException(net.dean.jraw.http.oauth.InvalidScopeException) ApiException(net.dean.jraw.ApiException) FontPreferences(me.ccrama.redditslide.Visuals.FontPreferences) ApiException(net.dean.jraw.ApiException)

Aggregations

View (android.view.View)18 OnSingleClickListener (me.ccrama.redditslide.util.OnSingleClickListener)18 TextView (android.widget.TextView)17 Intent (android.content.Intent)14 AlertDialogWrapper (com.afollestad.materialdialogs.AlertDialogWrapper)13 DialogInterface (android.content.DialogInterface)12 ImageView (android.widget.ImageView)12 RecyclerView (android.support.v7.widget.RecyclerView)10 SubmissionsView (me.ccrama.redditslide.Fragments.SubmissionsView)10 Snackbar (android.support.design.widget.Snackbar)9 LayoutInflater (android.view.LayoutInflater)9 SpoilerRobotoTextView (me.ccrama.redditslide.SpoilerRobotoTextView)9 ApiException (net.dean.jraw.ApiException)9 ArrayList (java.util.ArrayList)8 LinearLayout (android.widget.LinearLayout)7 SubredditView (me.ccrama.redditslide.Activities.SubredditView)7 Dialog (android.app.Dialog)6 MaterialDialog (com.afollestad.materialdialogs.MaterialDialog)6 CreateCardView (me.ccrama.redditslide.Views.CreateCardView)6 ActivityNotFoundException (android.content.ActivityNotFoundException)5