Search in sources :

Example 96 with Snackbar

use of com.google.android.material.snackbar.Snackbar in project Slide by ccrama.

the class MainActivity method onCreate.

@Override
protected void onCreate(final Bundle savedInstanceState) {
    inNightMode = SettingValues.isNight();
    disableSwipeBackLayout();
    super.onCreate(savedInstanceState);
    if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
        // Activity was brought to front and not created
        finish();
        return;
    }
    if (!Slide.hasStarted) {
        Slide.hasStarted = true;
    }
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        requestPermission();
    }
    boolean first = false;
    if (Reddit.colors != null && !Reddit.colors.contains("firstStart53")) {
        new AlertDialog.Builder(this).setTitle("Content settings have moved!").setMessage("NSFW content is now disabled by default. If you are over the age of 18, to re-enable NSFW content, visit Settings > Content settings").setPositiveButton(R.string.btn_ok, null).setCancelable(false).show();
        Reddit.colors.edit().putBoolean("firstStart53", true).apply();
    }
    if (Reddit.colors != null && !Reddit.colors.contains("Tutorial")) {
        first = true;
        if (Reddit.appRestart == null) {
            Reddit.appRestart = getSharedPreferences("appRestart", 0);
        }
        Reddit.appRestart.edit().putBoolean("firststart52", true).apply();
        Intent i = new Intent(this, Tutorial.class);
        doForcePrefs();
        startActivity(i);
    } else {
        if (Authentication.didOnline && NetworkUtil.isConnected(MainActivity.this) && !checkedPopups) {
            runAfterLoad = new Runnable() {

                @Override
                public void run() {
                    runAfterLoad = null;
                    if (Authentication.isLoggedIn) {
                        new AsyncNotificationBadge().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                    }
                    if (!Reddit.appRestart.getString(CheckForMail.SUBS_TO_GET, "").isEmpty()) {
                        new CheckForMail.AsyncGetSubs(MainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                    }
                    new AsyncTask<Void, Void, Submission>() {

                        @Override
                        protected Submission doInBackground(Void... params) {
                            if (Authentication.isLoggedIn)
                                UserSubscriptions.doOnlineSyncing();
                            try {
                                SubredditPaginator p = new SubredditPaginator(Authentication.reddit, "slideforreddit");
                                p.setLimit(2);
                                ArrayList<Submission> posts = new ArrayList<>(p.next());
                                for (Submission s : posts) {
                                    String version = BuildConfig.VERSION_NAME;
                                    if (version.length() > 5) {
                                        version = version.substring(0, version.lastIndexOf("."));
                                    }
                                    if (s.isStickied() && s.getSubmissionFlair().getText() != null && s.getSubmissionFlair().getText().equalsIgnoreCase("Announcement") && !Reddit.appRestart.contains("announcement" + s.getFullName()) && s.getTitle().contains(version)) {
                                        Reddit.appRestart.edit().putBoolean("announcement" + s.getFullName(), true).apply();
                                        return s;
                                    } else if (BuildConfig.VERSION_NAME.contains("alpha") && s.isStickied() && s.getSubmissionFlair().getText() != null && s.getSubmissionFlair().getText().equalsIgnoreCase("Alpha") && !Reddit.appRestart.contains("announcement" + s.getFullName()) && s.getTitle().contains(BuildConfig.VERSION_NAME)) {
                                        Reddit.appRestart.edit().putBoolean("announcement" + s.getFullName(), true).apply();
                                        return s;
                                    } else if (s.isStickied() && s.getSubmissionFlair().getText().equalsIgnoreCase("PRO") && !SettingValues.isPro && !Reddit.appRestart.contains("announcement" + s.getFullName())) {
                                        Reddit.appRestart.edit().putBoolean("announcement" + s.getFullName(), true).apply();
                                        return s;
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(final Submission s) {
                            checkedPopups = true;
                            if (s != null) {
                                Reddit.appRestart.edit().putString("page", s.getDataNode().get("selftext_html").asText()).apply();
                                Reddit.appRestart.edit().putString("title", s.getTitle()).apply();
                                Reddit.appRestart.edit().putString("url", s.getUrl()).apply();
                                String title;
                                if (s.getTitle().toLowerCase(Locale.ENGLISH).contains("release")) {
                                    title = getString(R.string.btn_changelog);
                                } else {
                                    title = getString(R.string.btn_view);
                                }
                                Snackbar snack = Snackbar.make(pager, s.getTitle(), Snackbar.LENGTH_INDEFINITE).setAction(title, new OnSingleClickListener() {

                                    @Override
                                    public void onSingleClick(View v) {
                                        Intent i = new Intent(MainActivity.this, Announcement.class);
                                        startActivity(i);
                                    }
                                });
                                LayoutUtils.showSnackbar(snack);
                            }
                        }
                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                // todo this  new AsyncStartNotifSocket().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                }
            };
        }
    }
    if (savedInstanceState != null && !changed) {
        Authentication.isLoggedIn = savedInstanceState.getBoolean(LOGGED_IN);
        Authentication.name = savedInstanceState.getString(USERNAME, "LOGGEDOUT");
        Authentication.didOnline = savedInstanceState.getBoolean(IS_ONLINE);
    } else {
        changed = false;
    }
    if (getIntent().getBooleanExtra("EXIT", false))
        finish();
    applyColorTheme();
    setContentView(R.layout.activity_overview);
    mToolbar = (Toolbar) findViewById(R.id.toolbar);
    mToolbar.setPopupTheme(new ColorPreferences(this).getFontStyle().getBaseId());
    setSupportActionBar(mToolbar);
    if (getIntent() != null && getIntent().hasExtra(EXTRA_PAGE_TO)) {
        toGoto = getIntent().getIntExtra(EXTRA_PAGE_TO, 0);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window window = this.getWindow();
        window.setStatusBarColor(Palette.getDarkerColor(Palette.getDarkerColor(Palette.getDefaultColor())));
    }
    mTabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
    header = findViewById(R.id.header);
    // Gets the height of the header
    if (header != null) {
        header.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                headerHeight = header.getHeight();
                header.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });
    }
    pager = (ToggleSwipeViewPager) findViewById(R.id.content_view);
    singleMode = SettingValues.single;
    if (singleMode) {
        commentPager = SettingValues.commentPager;
    }
    // Inflate tabs if single mode is disabled
    if (!singleMode) {
        mTabLayout = (TabLayout) ((ViewStub) findViewById(R.id.stub_tabs)).inflate();
    }
    // Disable swiping if single mode is enabled
    if (singleMode) {
        pager.setSwipingEnabled(false);
    }
    sidebarBody = (SpoilerRobotoTextView) findViewById(R.id.sidebar_text);
    sidebarOverflow = (CommentOverflow) findViewById(R.id.commentOverflow);
    if (!Reddit.appRestart.getBoolean("isRestarting", false) && Reddit.colors.contains("Tutorial")) {
        LogUtil.v("Starting main " + Authentication.name);
        Authentication.isLoggedIn = Reddit.appRestart.getBoolean("loggedin", false);
        Authentication.name = Reddit.appRestart.getString("name", "LOGGEDOUT");
        UserSubscriptions.doMainActivitySubs(this);
    } else if (!first) {
        LogUtil.v("Starting main 2 " + Authentication.name);
        Authentication.isLoggedIn = Reddit.appRestart.getBoolean("loggedin", false);
        Authentication.name = Reddit.appRestart.getString("name", "LOGGEDOUT");
        Reddit.appRestart.edit().putBoolean("isRestarting", false).commit();
        Reddit.isRestarting = false;
        UserSubscriptions.doMainActivitySubs(this);
    }
    final SharedPreferences seen = getSharedPreferences("SEEN", 0);
    if (!seen.contains("isCleared") && !seen.getAll().isEmpty() || !Reddit.appRestart.contains("hasCleared")) {
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                KVManger m = KVStore.getInstance();
                Map<String, ?> values = seen.getAll();
                for (Map.Entry<String, ?> entry : values.entrySet()) {
                    if (entry.getKey().length() == 6 && entry.getValue() instanceof Boolean) {
                        m.insert(entry.getKey(), "true");
                    } else if (entry.getValue() instanceof Long) {
                        m.insert(entry.getKey(), String.valueOf(seen.getLong(entry.getKey(), 0)));
                    }
                }
                seen.edit().clear().putBoolean("isCleared", true).apply();
                if (getSharedPreferences("HIDDEN_POSTS", 0).getAll().size() != 0) {
                    getSharedPreferences("HIDDEN", 0).edit().clear().apply();
                    getSharedPreferences("HIDDEN_POSTS", 0).edit().clear().apply();
                }
                if (!Reddit.appRestart.contains("hasCleared")) {
                    SharedPreferences.Editor e = Reddit.appRestart.edit();
                    Map<String, ?> toClear = Reddit.appRestart.getAll();
                    for (Map.Entry<String, ?> entry : toClear.entrySet()) {
                        if (entry.getValue() instanceof String && ((String) entry.getValue()).length() > 300) {
                            e.remove(entry.getKey());
                        }
                    }
                    e.putBoolean("hasCleared", true);
                    e.apply();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                dismissProgressDialog();
            }

            @Override
            protected void onPreExecute() {
                d = new MaterialDialog.Builder(MainActivity.this).title(R.string.misc_setting_up).content(R.string.misc_setting_up_message).progress(true, 100).cancelable(false).build();
                d.show();
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
    if (!BuildConfig.isFDroid && Authentication.isLoggedIn && NetworkUtil.isConnected(MainActivity.this)) {
        // Display an snackbar that asks the user to rate the app after this
        // activity was created 6 times, never again when once clicked or with a maximum of
        // two times.
        SnackEngage.from(MainActivity.this).withSnack(new RateSnack().withConditions(new NeverAgainWhenClickedOnce(), new AfterNumberOfOpportunities(10), new WithLimitedNumberOfTimes(2)).overrideActionText(getString(R.string.misc_rate_msg)).overrideTitleText(getString(R.string.misc_rate_title)).withDuration(BaseSnack.DURATION_LONG)).build().engageWhenAppropriate();
    }
    if (SettingValues.subredditSearchMethod == Constants.SUBREDDIT_SEARCH_METHOD_TOOLBAR || SettingValues.subredditSearchMethod == Constants.SUBREDDIT_SEARCH_METHOD_BOTH) {
        setupSubredditSearchToolbar();
    }
    /**
     * int for the current base theme selected.
     * 0 = Dark, 1 = Light, 2 = AMOLED, 3 = Dark blue, 4 = AMOLED with contrast, 5 = Sepia
     */
    SettingValues.currentTheme = new ColorPreferences(this).getFontStyle().getThemeType();
    networkStateReceiver = new NetworkStateReceiver();
    networkStateReceiver.addListener(this);
    try {
        this.registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
    } catch (Exception e) {
    }
    LogUtil.v("Installed browsers");
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setData(Uri.parse("http://ccrama.me/"));
    List<ResolveInfo> allApps = getPackageManager().queryIntentActivities(intent, PackageManager.GET_DISABLED_COMPONENTS);
    for (ResolveInfo i : allApps) {
        if (i.activityInfo.isEnabled())
            LogUtil.v(i.activityInfo.packageName);
    }
}
Also used : AlertDialog(androidx.appcompat.app.AlertDialog) RateSnack(org.ligi.snackengage.snacks.RateSnack) NeverAgainWhenClickedOnce(org.ligi.snackengage.conditions.NeverAgainWhenClickedOnce) OnSingleClickListener(me.ccrama.redditslide.util.OnSingleClickListener) ArrayList(java.util.ArrayList) CaseInsensitiveArrayList(me.ccrama.redditslide.CaseInsensitiveArrayList) AfterNumberOfOpportunities(org.ligi.snackengage.conditions.AfterNumberOfOpportunities) ResolveInfo(android.content.pm.ResolveInfo) SubredditPaginator(net.dean.jraw.paginators.SubredditPaginator) WithLimitedNumberOfTimes(org.ligi.snackengage.conditions.WithLimitedNumberOfTimes) ViewTreeObserver(android.view.ViewTreeObserver) Window(android.view.Window) IntentFilter(android.content.IntentFilter) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Submission(net.dean.jraw.models.Submission) ColorPreferences(me.ccrama.redditslide.Visuals.ColorPreferences) SharedPreferences(android.content.SharedPreferences) AsyncTask(android.os.AsyncTask) Intent(android.content.Intent) ImageView(android.widget.ImageView) HorizontalScrollView(android.widget.HorizontalScrollView) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) CardView(androidx.cardview.widget.CardView) AutoCompleteTextView(android.widget.AutoCompleteTextView) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) View(android.view.View) TextView(android.widget.TextView) ListView(android.widget.ListView) ApiException(net.dean.jraw.ApiException) NetworkException(net.dean.jraw.http.NetworkException) ViewStub(android.view.ViewStub) KVManger(com.lusfold.androidkeyvaluestore.core.KVManger) Map(java.util.Map) HashMap(java.util.HashMap) NetworkStateReceiver(me.ccrama.redditslide.util.NetworkStateReceiver) Snackbar(com.google.android.material.snackbar.Snackbar)

Example 97 with Snackbar

use of com.google.android.material.snackbar.Snackbar in project Slide by ccrama.

the class MainActivity method checkClipboard.

public void checkClipboard() {
    try {
        ClipboardManager clipboard = ContextCompat.getSystemService(this, ClipboardManager.class);
        if (clipboard != null && clipboard.hasPrimaryClip()) {
            ClipData data = clipboard.getPrimaryClip();
            final String s = (String) data.getItemAt(0).getText();
            if (!s.isEmpty()) {
                if (ContentType.getContentType(s) == ContentType.Type.REDDIT && !HasSeen.getSeen(s)) {
                    Snackbar snack = Snackbar.make(mToolbar, "Reddit link found in your clipboard", Snackbar.LENGTH_LONG);
                    snack.setAction("OPEN", new View.OnClickListener() {

                        @Override
                        public void onClick(View view) {
                            OpenRedditLink.openUrl(MainActivity.this, s, false);
                        }
                    });
                    snack.show();
                }
            }
        }
    } catch (Exception e) {
    }
}
Also used : ClipboardManager(android.content.ClipboardManager) ClipData(android.content.ClipData) ImageView(android.widget.ImageView) HorizontalScrollView(android.widget.HorizontalScrollView) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) CardView(androidx.cardview.widget.CardView) AutoCompleteTextView(android.widget.AutoCompleteTextView) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) View(android.view.View) TextView(android.widget.TextView) ListView(android.widget.ListView) ApiException(net.dean.jraw.ApiException) NetworkException(net.dean.jraw.http.NetworkException) Snackbar(com.google.android.material.snackbar.Snackbar)

Example 98 with Snackbar

use of com.google.android.material.snackbar.Snackbar 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 = 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 = SortingUtil.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();
                    }
                };
                new AlertDialog.Builder(SubredditView.this).setTitle(R.string.sorting_choose).setSingleChoiceItems(SortingUtil.getSortingStrings(), sortid, l2).setNegativeButton("Reset default sorting", (dialog, which) -> {
                    SettingValues.prefs.edit().remove("defaultSort" + subreddit.toLowerCase(Locale.ENGLISH)).apply();
                    SettingValues.prefs.edit().remove("defaultTime" + subreddit.toLowerCase(Locale.ENGLISH)).apply();
                    final TextView sort1 = dialoglayout.findViewById(R.id.sort);
                    if (SettingValues.hasSort(subreddit)) {
                        Sorting sortingis1 = SettingValues.getBaseSubmissionSort(subreddit);
                        sort1.setText(sortingis1.name() + ((sortingis1 == Sorting.CONTROVERSIAL || sortingis1 == Sorting.TOP) ? " of " + SettingValues.getBaseTimePeriod(subreddit).name() : ""));
                    } else {
                        sort1.setText("Set default sorting");
                    }
                    reloadSubs();
                }).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, (dialog1, 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) {
                                                                LayoutUtils.showSnackbar(s);
                                                            }
                                                        }
                                                    }.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) {
                                                        LayoutUtils.showSnackbar(s);
                                                    }
                                                }
                                            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                        }
                                    }
                                }).show();
                            }
                        });
                    }
                }
            }.execute((View) dialoglayout.findViewById(R.id.flair));
        }
    } else {
        if (drawerLayout != null) {
            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.END);
        }
    }
}
Also used : AlertDialog(androidx.appcompat.app.AlertDialog) 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) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) AlertDialog(androidx.appcompat.app.AlertDialog) Dialog(android.app.Dialog) NonNull(androidx.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.Visuals.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) NetworkException(net.dean.jraw.http.NetworkException) Sorting(net.dean.jraw.paginators.Sorting) ContextThemeWrapper(androidx.appcompat.view.ContextThemeWrapper) UserRecord(net.dean.jraw.models.UserRecord) DialogAction(com.afollestad.materialdialogs.DialogAction) LayoutInflater(android.view.LayoutInflater) AccountManager(net.dean.jraw.managers.AccountManager) Snackbar(com.google.android.material.snackbar.Snackbar)

Example 99 with Snackbar

use of com.google.android.material.snackbar.Snackbar in project Slide by ccrama.

the class PopulateSubmissionViewHolder method showBottomSheet.

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

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

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

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

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

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

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

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

Example 100 with Snackbar

use of com.google.android.material.snackbar.Snackbar in project Slide by ccrama.

the class PopulateSubmissionViewHolder method addClickFunctions.

private static void addClickFunctions(final View base, final ContentType.Type type, final Activity contextActivity, final Submission submission, final SubmissionViewHolder holder, final boolean full) {
    base.setOnClickListener(new OnSingleClickListener() {

        @Override
        public void onSingleClick(View v) {
            if (NetworkUtil.isConnected(contextActivity) || (!NetworkUtil.isConnected(contextActivity) && ContentType.fullImage(type))) {
                if (SettingValues.storeHistory && !full) {
                    if (!submission.isNsfw() || SettingValues.storeNSFWHistory) {
                        HasSeen.addSeen(submission.getFullName());
                        if (contextActivity instanceof MainActivity || contextActivity instanceof MultiredditOverview || contextActivity instanceof SubredditView || contextActivity instanceof Search || contextActivity instanceof Profile) {
                            holder.title.setAlpha(0.54f);
                            holder.body.setAlpha(0.54f);
                        }
                    }
                }
                if (!(contextActivity instanceof PeekViewActivity) || !((PeekViewActivity) contextActivity).isPeeking() || (base instanceof HeaderImageLinkView && ((HeaderImageLinkView) base).popped)) {
                    if (!PostMatch.openExternal(submission.getUrl()) || type == ContentType.Type.VIDEO) {
                        switch(type) {
                            case STREAMABLE:
                                if (SettingValues.video) {
                                    Intent myIntent = new Intent(contextActivity, MediaView.class);
                                    myIntent.putExtra(MediaView.SUBREDDIT, submission.getSubredditName());
                                    myIntent.putExtra(MediaView.EXTRA_URL, submission.getUrl());
                                    myIntent.putExtra(EXTRA_SUBMISSION_TITLE, submission.getTitle());
                                    PopulateBase.addAdaptorPosition(myIntent, submission, holder.getBindingAdapterPosition());
                                    contextActivity.startActivity(myIntent);
                                } else {
                                    LinkUtil.openExternally(submission.getUrl());
                                }
                                break;
                            case IMGUR:
                            case DEVIANTART:
                            case XKCD:
                            case IMAGE:
                                openImage(type, contextActivity, submission, holder.leadImage, holder.getBindingAdapterPosition());
                                break;
                            case EMBEDDED:
                                if (SettingValues.video) {
                                    String data = CompatUtil.fromHtml(submission.getDataNode().get("media_embed").get("content").asText()).toString();
                                    {
                                        Intent i = new Intent(contextActivity, FullscreenVideo.class);
                                        i.putExtra(FullscreenVideo.EXTRA_HTML, data);
                                        contextActivity.startActivity(i);
                                    }
                                } else {
                                    LinkUtil.openExternally(submission.getUrl());
                                }
                                break;
                            case REDDIT:
                                openRedditContent(submission.getUrl(), contextActivity);
                                break;
                            case REDDIT_GALLERY:
                                if (SettingValues.album) {
                                    Intent i;
                                    if (SettingValues.albumSwipe) {
                                        i = new Intent(contextActivity, RedditGalleryPager.class);
                                        i.putExtra(AlbumPager.SUBREDDIT, submission.getSubredditName());
                                    } else {
                                        i = new Intent(contextActivity, RedditGallery.class);
                                        i.putExtra(Album.SUBREDDIT, submission.getSubredditName());
                                    }
                                    i.putExtra(EXTRA_SUBMISSION_TITLE, submission.getTitle());
                                    i.putExtra(RedditGallery.SUBREDDIT, submission.getSubredditName());
                                    ArrayList<GalleryImage> urls = new ArrayList<>();
                                    JsonNode dataNode = submission.getDataNode();
                                    if (dataNode.has("gallery_data")) {
                                        JsonUtil.getGalleryData(dataNode, urls);
                                    } else if (dataNode.has("crosspost_parent_list")) {
                                        // Else, try getting crosspost gallery data
                                        JsonNode crosspost_parent = dataNode.get("crosspost_parent_list").get(0);
                                        if (crosspost_parent.has("gallery_data")) {
                                            JsonUtil.getGalleryData(crosspost_parent, urls);
                                        }
                                    }
                                    Bundle urlsBundle = new Bundle();
                                    urlsBundle.putSerializable(RedditGallery.GALLERY_URLS, urls);
                                    i.putExtras(urlsBundle);
                                    PopulateBase.addAdaptorPosition(i, submission, holder.getBindingAdapterPosition());
                                    contextActivity.startActivity(i);
                                    contextActivity.overridePendingTransition(R.anim.slideright, R.anim.fade_out);
                                } else {
                                    LinkUtil.openExternally(submission.getUrl());
                                }
                                break;
                            case LINK:
                                LinkUtil.openUrl(submission.getUrl(), Palette.getColor(submission.getSubredditName()), contextActivity, holder.getBindingAdapterPosition(), submission);
                                break;
                            case SELF:
                                if (holder != null) {
                                    OnSingleClickListener.override = true;
                                    holder.itemView.performClick();
                                }
                                break;
                            case ALBUM:
                                if (SettingValues.album) {
                                    Intent i;
                                    if (SettingValues.albumSwipe) {
                                        i = new Intent(contextActivity, AlbumPager.class);
                                        i.putExtra(AlbumPager.SUBREDDIT, submission.getSubredditName());
                                    } else {
                                        i = new Intent(contextActivity, Album.class);
                                        i.putExtra(Album.SUBREDDIT, submission.getSubredditName());
                                    }
                                    i.putExtra(EXTRA_SUBMISSION_TITLE, submission.getTitle());
                                    i.putExtra(Album.EXTRA_URL, submission.getUrl());
                                    PopulateBase.addAdaptorPosition(i, submission, holder.getBindingAdapterPosition());
                                    contextActivity.startActivity(i);
                                    contextActivity.overridePendingTransition(R.anim.slideright, R.anim.fade_out);
                                } else {
                                    LinkUtil.openExternally(submission.getUrl());
                                }
                                break;
                            case TUMBLR:
                                if (SettingValues.album) {
                                    Intent i;
                                    if (SettingValues.albumSwipe) {
                                        i = new Intent(contextActivity, TumblrPager.class);
                                        i.putExtra(TumblrPager.SUBREDDIT, submission.getSubredditName());
                                    } else {
                                        i = new Intent(contextActivity, Tumblr.class);
                                        i.putExtra(Tumblr.SUBREDDIT, submission.getSubredditName());
                                    }
                                    i.putExtra(Album.EXTRA_URL, submission.getUrl());
                                    PopulateBase.addAdaptorPosition(i, submission, holder.getBindingAdapterPosition());
                                    contextActivity.startActivity(i);
                                    contextActivity.overridePendingTransition(R.anim.slideright, R.anim.fade_out);
                                } else {
                                    LinkUtil.openExternally(submission.getUrl());
                                }
                                break;
                            case VREDDIT_REDIRECT:
                            case GIF:
                            case VREDDIT_DIRECT:
                                openGif(contextActivity, submission, holder.getBindingAdapterPosition());
                                break;
                            case NONE:
                                if (holder != null) {
                                    holder.itemView.performClick();
                                }
                                break;
                            case VIDEO:
                                if (!LinkUtil.tryOpenWithVideoPlugin(submission.getUrl())) {
                                    LinkUtil.openUrl(submission.getUrl(), Palette.getStatusBarColor(), contextActivity);
                                }
                                break;
                        }
                    } else {
                        LinkUtil.openExternally(submission.getUrl());
                    }
                }
            } else {
                if (!(contextActivity instanceof PeekViewActivity) || !((PeekViewActivity) contextActivity).isPeeking()) {
                    Snackbar s = Snackbar.make(holder.itemView, R.string.go_online_view_content, Snackbar.LENGTH_SHORT);
                    LayoutUtils.showSnackbar(s);
                }
            }
        }
    });
}
Also used : MultiredditOverview(me.ccrama.redditslide.Activities.MultiredditOverview) Bundle(android.os.Bundle) OnSingleClickListener(me.ccrama.redditslide.util.OnSingleClickListener) ArrayList(java.util.ArrayList) SubredditView(me.ccrama.redditslide.Activities.SubredditView) Intent(android.content.Intent) JsonNode(com.fasterxml.jackson.databind.JsonNode) MainActivity(me.ccrama.redditslide.Activities.MainActivity) MediaView(me.ccrama.redditslide.Activities.MediaView) ImageView(android.widget.ImageView) CreateCardView(me.ccrama.redditslide.Views.CreateCardView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) TextView(android.widget.TextView) SubredditView(me.ccrama.redditslide.Activities.SubredditView) Profile(me.ccrama.redditslide.Activities.Profile) MediaView(me.ccrama.redditslide.Activities.MediaView) Search(me.ccrama.redditslide.Activities.Search) PeekViewActivity(me.ccrama.redditslide.ForceTouch.PeekViewActivity) Snackbar(com.google.android.material.snackbar.Snackbar)

Aggregations

Snackbar (com.google.android.material.snackbar.Snackbar)110 View (android.view.View)61 Intent (android.content.Intent)46 TextView (android.widget.TextView)41 AlertDialog (androidx.appcompat.app.AlertDialog)29 Context (android.content.Context)28 ImageView (android.widget.ImageView)28 LayoutInflater (android.view.LayoutInflater)24 ArrayList (java.util.ArrayList)23 RecyclerView (androidx.recyclerview.widget.RecyclerView)22 Bundle (android.os.Bundle)20 MaterialDialog (com.afollestad.materialdialogs.MaterialDialog)20 DialogInterface (android.content.DialogInterface)19 List (java.util.List)19 CreateCardView (me.ccrama.redditslide.Views.CreateCardView)18 Submission (net.dean.jraw.models.Submission)18 SubredditView (me.ccrama.redditslide.Activities.SubredditView)17 ApiException (net.dean.jraw.ApiException)17 Activity (android.app.Activity)16 OnSingleClickListener (me.ccrama.redditslide.util.OnSingleClickListener)16