Search in sources :

Example 36 with SwipeRefreshLayout

use of androidx.swiperefreshlayout.widget.SwipeRefreshLayout in project Carbon by ZieIony.

the class PaginationActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    initToolbar();
    SwipeRefreshLayout swipeRefresh = findViewById(R.id.swipeRefresh);
    final RecyclerView recyclerView = findViewById(R.id.recyclerView);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    fruitAdapter = new RowListAdapter<>(String.class, TextRow::new);
    recyclerView.setAdapter(fruitAdapter);
    recyclerView.setPagination(new RecyclerView.Pagination(layoutManager) {

        @Override
        protected boolean isLoading() {
            return swipeRefresh.isRefreshing();
        }

        @Override
        protected boolean isLastPage() {
            return page == 10;
        }

        @Override
        protected void loadNextPage() {
            swipeRefresh.setRefreshing(true);
            PaginationActivity.this.loadNextPage();
            swipeRefresh.setRefreshing(false);
        }
    });
    swipeRefresh.setOnRefreshListener(() -> {
        fruitAdapter.setItems(new ArrayList<>());
        page = 1;
        loadNextPage();
        swipeRefresh.setRefreshing(false);
    });
}
Also used : RecyclerView(carbon.widget.RecyclerView) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) SwipeRefreshLayout(androidx.swiperefreshlayout.widget.SwipeRefreshLayout)

Example 37 with SwipeRefreshLayout

use of androidx.swiperefreshlayout.widget.SwipeRefreshLayout in project BetterBatteryStats by asksven.

the class StatsActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.stats);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle(getString(R.string.app_name));
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayUseLogoEnabled(false);
    // set debugging
    if (sharedPrefs.getBoolean("debug_logging", false)) {
        LogSettings.DEBUG = true;
        CommonLogSettings.DEBUG = true;
    } else {
        LogSettings.DEBUG = false;
        CommonLogSettings.DEBUG = false;
    }
    swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
    swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            doRefresh(true);
        }
    });
    // /////////////////////////////////////////////
    // check if we have a new release
    // /////////////////////////////////////////////
    // if yes do some migration (if required) and show release notes
    String strLastRelease = sharedPrefs.getString("last_release", "0");
    String strCurrentRelease = "";
    try {
        PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        strCurrentRelease = Integer.toString(pinfo.versionCode);
    } catch (Exception e) {
    // nop strCurrentRelease is set to ""
    }
    // Grant permissions if they are missing and root is available
    if (!SysUtils.hasBatteryStatsPermission(this) || !SysUtils.hasDumpsysPermission(this) || !SysUtils.hasPackageUsageStatsPermission(this)) {
        if ((RootShell.getInstance().isRooted())) {
            // attempt to set perms using pm-comand
            Log.i(TAG, "attempting to grant perms with 'pm grant'");
            String pkg = this.getPackageName();
            RootShell.getInstance().run("pm grant " + pkg + " android.permission.BATTERY_STATS");
            RootShell.getInstance().run("pm grant " + pkg + " android.permission.DUMP");
            RootShell.getInstance().run("pm grant " + pkg + " android.permission.PACKAGE_USAGE_STATS");
            if (SysUtils.hasBatteryStatsPermission(this)) {
                Log.i(TAG, "succeeded");
            } else {
                Log.i(TAG, "failed");
            }
        }
    }
    // On Pie we disable private API checks
    if (Build.VERSION.SDK_INT >= 28) {
        NonRootShell.getInstance().run("settings put global hidden_api_policy_pre_p_apps 0");
        NonRootShell.getInstance().run("settings put global hidden_api_policy_p_apps 0");
    }
    // show install as system app screen if root available but perms missing
    if (!SystemAppActivity.hasAllPermissions(this)) // if (!SysUtils.hasBatteryStatsPermission(this) || !SysUtils.hasDumpsysPermission(this) || !SysUtils.hasPackageUsageStatsPermission(this))
    {
        Intent intentSystemApp = new Intent(this, SystemAppActivity.class);
        this.startActivity(intentSystemApp);
    }
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    // first start
    if (strLastRelease.equals("0")) {
        boolean firstLaunch = !prefs.getBoolean("launched", false);
        if (firstLaunch) {
            // Save that the app has been launched
            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean("launched", true);
            editor.commit();
            // start service to persist reference
            Intent serviceIntent = new Intent(this, WriteUnpluggedReferenceService.class);
            this.startService(serviceIntent);
            // refresh widgets
            Intent intentRefreshWidgets = new Intent(AppWidget.WIDGET_UPDATE);
            this.sendBroadcast(intentRefreshWidgets);
        }
        SharedPreferences.Editor updater = sharedPrefs.edit();
        updater.putString("last_release", strCurrentRelease);
        updater.commit();
    } else if (!strLastRelease.equals(strCurrentRelease)) {
        // save the current release to properties so that the dialog won't be shown till next version
        SharedPreferences.Editor updater = sharedPrefs.edit();
        updater.putString("last_release", strCurrentRelease);
        updater.commit();
    }
    // /////////////////////////////////////////////
    // retrieve default selections for spinners
    // if none were passed
    // /////////////////////////////////////////////
    m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0"));
    m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
    if (!ReferenceStore.hasReferenceByName(m_refFromName, this)) {
        m_refFromName = Reference.BOOT_REF_FILENAME;
        Toast.makeText(this, getString(R.string.info_fallback_to_boot), Toast.LENGTH_SHORT).show();
    }
    if (LogSettings.DEBUG)
        Log.i(TAG, "onCreate state from preferences: refFrom=" + m_refFromName + " refTo=" + m_refToName);
    try {
        // recover any saved state
        if ((savedInstanceState != null) && (!savedInstanceState.isEmpty())) {
            m_iStat = (Integer) savedInstanceState.getSerializable("stat");
            m_refFromName = (String) savedInstanceState.getSerializable("stattypeFrom");
            m_refToName = (String) savedInstanceState.getSerializable("stattypeTo");
            if (LogSettings.DEBUG)
                Log.i(TAG, "onCreate retrieved saved state: refFrom=" + m_refFromName + " refTo=" + m_refToName);
        }
    } catch (Exception e) {
        m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0"));
        m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
        Log.e(TAG, "Exception: " + e.getMessage());
        DataStorage.LogToFile(LOGFILE, "Exception in onCreate restoring Bundle");
        DataStorage.LogToFile(LOGFILE, e.getMessage());
        DataStorage.LogToFile(LOGFILE, e.getStackTrace());
        Toast.makeText(this, getString(R.string.info_state_recovery_error), Toast.LENGTH_SHORT).show();
    }
    // Handle the case the Activity was called from an intent with paramaters
    Bundle extras = getIntent().getExtras();
    if ((extras != null) && !extras.isEmpty()) {
        // Override if some values were passed to the intent
        if (extras.containsKey(StatsActivity.STAT))
            m_iStat = extras.getInt(StatsActivity.STAT);
        if (extras.containsKey(StatsActivity.STAT_TYPE_FROM))
            m_refFromName = extras.getString(StatsActivity.STAT_TYPE_FROM);
        if (extras.containsKey(StatsActivity.STAT_TYPE_TO))
            m_refToName = extras.getString(StatsActivity.STAT_TYPE_TO);
        if (LogSettings.DEBUG)
            Log.i(TAG, "onCreate state from extra: refFrom=" + m_refFromName + " refTo=" + m_refToName);
    }
    // Spinner for selecting the stat
    Spinner spinnerStat = (Spinner) findViewById(R.id.spinnerStat);
    ArrayAdapter spinnerStatAdapter = ArrayAdapter.createFromResource(this, R.array.stats, // android.R.layout.simple_spinner_item);
    R.layout.bbs_spinner_layout);
    // android.R.layout.simple_spinner_dropdown_item);
    spinnerStatAdapter.setDropDownViewResource(R.layout.bbs_spinner_dropdown_item);
    spinnerStat.setAdapter(spinnerStatAdapter);
    // setSelection MUST be called after setAdapter
    spinnerStat.setSelection(m_iStat);
    spinnerStat.setOnItemSelectedListener(this);
    // /////////////////////////////////////////////
    // Spinner for Selecting the Stat type
    // /////////////////////////////////////////////
    Spinner spinnerStatType = (Spinner) findViewById(R.id.spinnerStatType);
    // android.R.layout.simple_spinner_item);
    m_spinnerFromAdapter = new ReferencesAdapter(this, R.layout.bbs_spinner_layout);
    // android.R.layout.simple_spinner_dropdown_item);
    m_spinnerFromAdapter.setDropDownViewResource(R.layout.bbs_spinner_dropdown_item);
    spinnerStatType.setAdapter(m_spinnerFromAdapter);
    try {
        this.setListViewAdapter();
    } catch (BatteryInfoUnavailableException e) {
        Log.e(TAG, "Exception: " + Log.getStackTraceString(e));
        Snackbar.make(findViewById(android.R.id.content), R.string.info_service_connection_error, Snackbar.LENGTH_LONG).show();
    // Toast.makeText(this,
    // getString(R.string.info_service_connection_error),
    // Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        // Log.e(TAG, e.getMessage(), e.fillInStackTrace());
        Log.e(TAG, "Exception: " + Log.getStackTraceString(e));
        Toast.makeText(this, getString(R.string.info_unknown_stat_error), Toast.LENGTH_LONG).show();
    }
    // setSelection MUST be called after setAdapter
    spinnerStatType.setSelection(m_spinnerFromAdapter.getPosition(m_refFromName));
    spinnerStatType.setOnItemSelectedListener(this);
    // /////////////////////////////////////////////
    // Spinner for Selecting the end sample
    // /////////////////////////////////////////////
    Spinner spinnerStatSampleEnd = (Spinner) findViewById(R.id.spinnerStatSampleEnd);
    // android.R.layout.simple_spinner_item);
    m_spinnerToAdapter = new ReferencesAdapter(this, R.layout.bbs_spinner_layout);
    // android.R.layout.simple_spinner_dropdown_item);
    m_spinnerToAdapter.setDropDownViewResource(R.layout.bbs_spinner_dropdown_item);
    spinnerStatSampleEnd.setVisibility(View.VISIBLE);
    spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter);
    // setSelection must be called after setAdapter
    if ((m_refToName != null) && !m_refToName.equals("")) {
        int pos = m_spinnerToAdapter.getPosition(m_refToName);
        spinnerStatSampleEnd.setSelection(pos);
    } else {
        spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME));
    }
    spinnerStatSampleEnd.setOnItemSelectedListener(this);
    // /////////////////////////////////////////////
    // sorting
    // /////////////////////////////////////////////
    m_iSorting = 0;
    // log reference store
    ReferenceStore.logReferences(this);
    if (LogSettings.DEBUG) {
        Log.i(TAG, "onCreate final state: refFrom=" + m_refFromName + " refTo=" + m_refToName);
        Log.i(TAG, "OnCreated end");
    }
}
Also used : SharedPreferences(android.content.SharedPreferences) PackageInfo(android.content.pm.PackageInfo) Bundle(android.os.Bundle) Spinner(android.widget.Spinner) Intent(android.content.Intent) SwipeRefreshLayout(androidx.swiperefreshlayout.widget.SwipeRefreshLayout) BatteryInfoUnavailableException(com.asksven.android.common.privateapiproxies.BatteryInfoUnavailableException) ReferencesAdapter(com.asksven.betterbatterystats.adapters.ReferencesAdapter) BatteryInfoUnavailableException(com.asksven.android.common.privateapiproxies.BatteryInfoUnavailableException) ArrayAdapter(android.widget.ArrayAdapter) Toolbar(androidx.appcompat.widget.Toolbar)

Example 38 with SwipeRefreshLayout

use of androidx.swiperefreshlayout.widget.SwipeRefreshLayout in project BetterBatteryStats by asksven.

the class RawStatsActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.raw_stats);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle(getString(R.string.label_raw_stats));
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayUseLogoEnabled(false);
    swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
    swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            doRefresh();
        }
    });
    // Spinner for selecting the stat
    Spinner spinnerStat = (Spinner) findViewById(R.id.spinnerStat);
    ArrayAdapter spinnerStatAdapter = ArrayAdapter.createFromResource(this, R.array.stats, R.layout.bbs_spinner_layout);
    spinnerStatAdapter.setDropDownViewResource(R.layout.bbs_spinner_dropdown_item);
    spinnerStat.setAdapter(spinnerStatAdapter);
    // setSelection MUST be called after setAdapter
    spinnerStat.setSelection(m_iStat);
    spinnerStat.setOnItemSelectedListener(this);
    TextView tvSince = (TextView) findViewById(R.id.TextViewSince);
    long sinceMs = SystemClock.elapsedRealtime();
    if (sinceMs != -1) {
        String sinceText = DateUtils.formatDuration(sinceMs);
        tvSince.setText(sinceText);
        Log.i(TAG, "Since " + sinceText);
    } else {
        tvSince.setText("n/a ");
        Log.i(TAG, "Since: n/a ");
    }
}
Also used : Spinner(android.widget.Spinner) TextView(android.widget.TextView) SwipeRefreshLayout(androidx.swiperefreshlayout.widget.SwipeRefreshLayout) ArrayAdapter(android.widget.ArrayAdapter) Toolbar(androidx.appcompat.widget.Toolbar)

Example 39 with SwipeRefreshLayout

use of androidx.swiperefreshlayout.widget.SwipeRefreshLayout in project Slide by ccrama.

the class SubmissionsView method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), new ColorPreferences(inflater.getContext()).getThemeSubreddit(id));
    final View v = LayoutInflater.from(contextThemeWrapper).inflate(R.layout.fragment_verticalcontent, container, false);
    if (getActivity() instanceof MainActivity) {
        v.findViewById(R.id.back).setBackgroundResource(0);
    }
    rv = v.findViewById(R.id.vertical_content);
    rv.setHasFixedSize(true);
    final RecyclerView.LayoutManager mLayoutManager = createLayoutManager(LayoutUtils.getNumColumns(getResources().getConfiguration().orientation, getActivity()));
    if (!(getActivity() instanceof SubredditView)) {
        v.findViewById(R.id.back).setBackground(null);
    }
    rv.setLayoutManager(mLayoutManager);
    rv.setItemAnimator(new SlideUpAlphaAnimator().withInterpolator(new LinearOutSlowInInterpolator()));
    rv.getLayoutManager().scrollToPosition(0);
    mSwipeRefreshLayout = v.findViewById(R.id.activity_main_swipe_refresh_layout);
    mSwipeRefreshLayout.setColorSchemeColors(Palette.getColors(id, getContext()));
    /**
     * If using List view mode, we need to remove the start margin from the SwipeRefreshLayout.
     * The scrollbar style of "outsideInset" creates a 4dp padding around it. To counter this,
     * change the scrollbar style to "insideOverlay" when list view is enabled.
     * To recap: this removes the margins from the start/end so list view is full-width.
     */
    if (SettingValues.defaultCardView == CreateCardView.CardEnum.LIST) {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        MarginLayoutParamsCompat.setMarginStart(params, 0);
        rv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mSwipeRefreshLayout.setLayoutParams(params);
    }
    /**
     * If we use 'findViewById(R.id.header).getMeasuredHeight()', 0 is always returned.
     * So, we estimate the height of the header in dp.
     * If the view type is "single" (and therefore "commentPager"), we need a different offset
     */
    final int HEADER_OFFSET = (SettingValues.single || getActivity() instanceof SubredditView) ? Constants.SINGLE_HEADER_VIEW_OFFSET : Constants.TAB_HEADER_VIEW_OFFSET;
    mSwipeRefreshLayout.setProgressViewOffset(false, HEADER_OFFSET - Constants.PTR_OFFSET_TOP, HEADER_OFFSET + Constants.PTR_OFFSET_BOTTOM);
    if (SettingValues.fab) {
        fab = v.findViewById(R.id.post_floating_action_button);
        if (SettingValues.fabType == Constants.FAB_POST) {
            fab.setImageResource(R.drawable.ic_add);
            fab.setContentDescription(getString(R.string.btn_fab_post));
            fab.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent inte = new Intent(getActivity(), Submit.class);
                    inte.putExtra(Submit.EXTRA_SUBREDDIT, id);
                    getActivity().startActivity(inte);
                }
            });
        } else if (SettingValues.fabType == Constants.FAB_SEARCH) {
            fab.setImageResource(R.drawable.ic_search);
            fab.setContentDescription(getString(R.string.btn_fab_search));
            fab.setOnClickListener(new View.OnClickListener() {

                String term;

                @Override
                public void onClick(View v) {
                    MaterialDialog.Builder builder = new MaterialDialog.Builder(getActivity()).title(R.string.search_title).alwaysCallInputCallback().input(getString(R.string.search_msg), "", new MaterialDialog.InputCallback() {

                        @Override
                        public void onInput(MaterialDialog materialDialog, CharSequence charSequence) {
                            term = charSequence.toString();
                        }
                    });
                    // Add "search current sub" if it is not frontpage/all/random
                    if (!id.equalsIgnoreCase("frontpage") && !id.equalsIgnoreCase("all") && !id.contains(".") && !id.contains("/m/") && !id.equalsIgnoreCase("friends") && !id.equalsIgnoreCase("random") && !id.equalsIgnoreCase("popular") && !id.equalsIgnoreCase("myrandom") && !id.equalsIgnoreCase("randnsfw")) {
                        builder.positiveText(getString(R.string.search_subreddit, id)).onPositive(new MaterialDialog.SingleButtonCallback() {

                            @Override
                            public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {
                                Intent i = new Intent(getActivity(), Search.class);
                                i.putExtra(Search.EXTRA_TERM, term);
                                i.putExtra(Search.EXTRA_SUBREDDIT, id);
                                startActivity(i);
                            }
                        });
                        builder.neutralText(R.string.search_all).onNeutral(new MaterialDialog.SingleButtonCallback() {

                            @Override
                            public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {
                                Intent i = new Intent(getActivity(), Search.class);
                                i.putExtra(Search.EXTRA_TERM, term);
                                startActivity(i);
                            }
                        });
                    } else {
                        builder.positiveText(R.string.search_all).onPositive(new MaterialDialog.SingleButtonCallback() {

                            @Override
                            public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {
                                Intent i = new Intent(getActivity(), Search.class);
                                i.putExtra(Search.EXTRA_TERM, term);
                                startActivity(i);
                            }
                        });
                    }
                    builder.show();
                }
            });
        } else {
            fab.setImageResource(R.drawable.ic_visibility_off);
            fab.setContentDescription(getString(R.string.btn_fab_hide));
            fab.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (!Reddit.fabClear) {
                        new AlertDialog.Builder(getActivity()).setTitle(R.string.settings_fabclear).setMessage(R.string.settings_fabclear_msg).setPositiveButton(R.string.btn_ok, (dialog, which) -> {
                            Reddit.colors.edit().putBoolean(SettingValues.PREF_FAB_CLEAR, true).apply();
                            Reddit.fabClear = true;
                            clearSeenPosts(false);
                        }).show();
                    } else {
                        clearSeenPosts(false);
                    }
                }
            });
            final Handler handler = new Handler();
            fab.setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    detector.onTouchEvent(event);
                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        origY = event.getY();
                        handler.postDelayed(mLongPressRunnable, android.view.ViewConfiguration.getLongPressTimeout());
                    }
                    if (((event.getAction() == MotionEvent.ACTION_MOVE) && Math.abs(event.getY() - origY) > fab.getHeight() / 2.0f) || (event.getAction() == MotionEvent.ACTION_UP)) {
                        handler.removeCallbacks(mLongPressRunnable);
                    }
                    return false;
                }
            });
            mLongPressRunnable = new Runnable() {

                public void run() {
                    fab.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
                    if (!Reddit.fabClear) {
                        new AlertDialog.Builder(getActivity()).setTitle(R.string.settings_fabclear).setMessage(R.string.settings_fabclear_msg).setPositiveButton(R.string.btn_ok, (dialog, which) -> {
                            Reddit.colors.edit().putBoolean(SettingValues.PREF_FAB_CLEAR, true).apply();
                            Reddit.fabClear = true;
                            clearSeenPosts(true);
                        }).show();
                    } else {
                        clearSeenPosts(true);
                    }
                    Snackbar s = Snackbar.make(rv, getResources().getString(R.string.posts_hidden_forever), Snackbar.LENGTH_LONG);
                    /*Todo a way to unhide
                        s.setAction(R.string.btn_undo, new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {

                            }
                        });*/
                    LayoutUtils.showSnackbar(s);
                }
            };
        }
    } else {
        v.findViewById(R.id.post_floating_action_button).setVisibility(View.GONE);
    }
    if (fab != null)
        fab.show();
    header = getActivity().findViewById(R.id.header);
    // TODO, have it so that if the user clicks anywhere in the rv to hide and cancel GoToSubreddit?
    // final TextInputEditText GO_TO_SUB_FIELD = (TextInputEditText) getActivity().findViewById(R.id.toolbar_search);
    // final Toolbar TOOLBAR = ((Toolbar) getActivity().findViewById(R.id.toolbar));
    // final String PREV_TITLE = TOOLBAR.getTitle().toString();
    // final ImageView CLOSE_BUTTON = (ImageView) getActivity().findViewById(R.id.close);
    // 
    // rv.setOnTouchListener(new View.OnTouchListener() {
    // @Override
    // public boolean onTouch(View v, MotionEvent event) {
    // System.out.println("touched");
    // KeyboardUtil.hideKeyboard(getActivity(), v.getWindowToken(), 0);
    // 
    // GO_TO_SUB_FIELD.setText("");
    // GO_TO_SUB_FIELD.setVisibility(View.GONE);
    // CLOSE_BUTTON.setVisibility(View.GONE);
    // TOOLBAR.setTitle(PREV_TITLE);
    // 
    // return false;
    // }
    // });
    resetScroll();
    Reddit.isLoading = false;
    if (MainActivity.shouldLoad == null || id == null || (MainActivity.shouldLoad != null && MainActivity.shouldLoad.equals(id)) || !(getActivity() instanceof MainActivity)) {
        doAdapter();
    }
    return v;
}
Also used : Bundle(android.os.Bundle) R(me.ccrama.redditslide.R) NonNull(androidx.annotation.NonNull) MainActivity(me.ccrama.redditslide.Activities.MainActivity) Locale(java.util.Locale) Handler(android.os.Handler) FloatingActionButton(com.google.android.material.floatingactionbutton.FloatingActionButton) Fragment(androidx.fragment.app.Fragment) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) SubredditPosts(me.ccrama.redditslide.Adapters.SubredditPosts) MarginLayoutParamsCompat(androidx.core.view.MarginLayoutParamsCompat) Palette(me.ccrama.redditslide.Visuals.Palette) ViewGroup(android.view.ViewGroup) CatchStaggeredGridLayoutManager(me.ccrama.redditslide.Views.CatchStaggeredGridLayoutManager) HapticFeedbackConstants(android.view.HapticFeedbackConstants) OfflineSubreddit(me.ccrama.redditslide.OfflineSubreddit) List(java.util.List) RelativeLayout(android.widget.RelativeLayout) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Snackbar(com.google.android.material.snackbar.Snackbar) LayoutUtils(me.ccrama.redditslide.util.LayoutUtils) Context(android.content.Context) LinearOutSlowInInterpolator(androidx.interpolator.view.animation.LinearOutSlowInInterpolator) GestureDetector(android.view.GestureDetector) BaseActivity(me.ccrama.redditslide.Activities.BaseActivity) SettingValues(me.ccrama.redditslide.SettingValues) AlertDialog(androidx.appcompat.app.AlertDialog) HasSeen(me.ccrama.redditslide.HasSeen) Submission(net.dean.jraw.models.Submission) Intent(android.content.Intent) Constants(me.ccrama.redditslide.Constants) Hidden(me.ccrama.redditslide.Hidden) MotionEvent(android.view.MotionEvent) Search(me.ccrama.redditslide.Activities.Search) SubredditView(me.ccrama.redditslide.Activities.SubredditView) SubmissionAdapter(me.ccrama.redditslide.Adapters.SubmissionAdapter) AlphaInAnimator(com.mikepenz.itemanimators.AlphaInAnimator) LayoutInflater(android.view.LayoutInflater) SwipeRefreshLayout(androidx.swiperefreshlayout.widget.SwipeRefreshLayout) Reddit(me.ccrama.redditslide.Reddit) DialogAction(com.afollestad.materialdialogs.DialogAction) Submit(me.ccrama.redditslide.Activities.Submit) ColorPreferences(me.ccrama.redditslide.Visuals.ColorPreferences) ToolbarScrollHideHandler(me.ccrama.redditslide.handler.ToolbarScrollHideHandler) ContextThemeWrapper(androidx.appcompat.view.ContextThemeWrapper) SubmissionDisplay(me.ccrama.redditslide.Adapters.SubmissionDisplay) SlideUpAlphaAnimator(com.mikepenz.itemanimators.SlideUpAlphaAnimator) Configuration(android.content.res.Configuration) CreateCardView(me.ccrama.redditslide.Views.CreateCardView) SubredditView(me.ccrama.redditslide.Activities.SubredditView) MainActivity(me.ccrama.redditslide.Activities.MainActivity) SlideUpAlphaAnimator(com.mikepenz.itemanimators.SlideUpAlphaAnimator) LinearOutSlowInInterpolator(androidx.interpolator.view.animation.LinearOutSlowInInterpolator) Search(me.ccrama.redditslide.Activities.Search) Context(android.content.Context) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) ColorPreferences(me.ccrama.redditslide.Visuals.ColorPreferences) Handler(android.os.Handler) ToolbarScrollHideHandler(me.ccrama.redditslide.handler.ToolbarScrollHideHandler) Intent(android.content.Intent) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) SubredditView(me.ccrama.redditslide.Activities.SubredditView) CreateCardView(me.ccrama.redditslide.Views.CreateCardView) MotionEvent(android.view.MotionEvent) ContextThemeWrapper(androidx.appcompat.view.ContextThemeWrapper) DialogAction(com.afollestad.materialdialogs.DialogAction) RelativeLayout(android.widget.RelativeLayout) Submit(me.ccrama.redditslide.Activities.Submit) RecyclerView(androidx.recyclerview.widget.RecyclerView) Snackbar(com.google.android.material.snackbar.Snackbar)

Example 40 with SwipeRefreshLayout

use of androidx.swiperefreshlayout.widget.SwipeRefreshLayout in project Slide by ccrama.

the class ContributionsView method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_verticalcontent, container, false);
    final RecyclerView rv = v.findViewById(R.id.vertical_content);
    final PreCachingLayoutManager mLayoutManager = new PreCachingLayoutManager(getContext());
    rv.setLayoutManager(mLayoutManager);
    rv.setItemViewCacheSize(2);
    v.findViewById(R.id.post_floating_action_button).setVisibility(View.GONE);
    final SwipeRefreshLayout mSwipeRefreshLayout = v.findViewById(R.id.activity_main_swipe_refresh_layout);
    mSwipeRefreshLayout.setColorSchemeColors(Palette.getColors(id, getActivity()));
    // If we use 'findViewById(R.id.header).getMeasuredHeight()', 0 is always returned.
    // So, we estimate the height of the header in dp
    mSwipeRefreshLayout.setProgressViewOffset(false, Constants.TAB_HEADER_VIEW_OFFSET - Constants.PTR_OFFSET_TOP, Constants.TAB_HEADER_VIEW_OFFSET + Constants.PTR_OFFSET_BOTTOM);
    mSwipeRefreshLayout.post(new Runnable() {

        @Override
        public void run() {
            mSwipeRefreshLayout.setRefreshing(true);
        }
    });
    if (where.equals("saved") && getActivity() instanceof Profile)
        posts = new ContributionPostsSaved(id, where, ((Profile) getActivity()).category);
    else
        posts = new ContributionPosts(id, where);
    // noinspection StringEquality
    if (where == "hidden")
        adapter = new ContributionAdapter(getActivity(), posts, rv, true);
    else
        adapter = new ContributionAdapter(getActivity(), posts, rv);
    rv.setAdapter(adapter);
    posts.bindAdapter(adapter, mSwipeRefreshLayout);
    // TODO catch errors
    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            posts.loadMore(adapter, id, true);
        // TODO catch errors
        }
    });
    rv.addOnScrollListener(new ToolbarScrollHideHandler(getActivity().findViewById(R.id.toolbar), getActivity().findViewById(R.id.header)) {

        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            visibleItemCount = rv.getLayoutManager().getChildCount();
            totalItemCount = rv.getLayoutManager().getItemCount();
            if (rv.getLayoutManager() instanceof PreCachingLayoutManager) {
                pastVisiblesItems = ((PreCachingLayoutManager) rv.getLayoutManager()).findFirstVisibleItemPosition();
            } else {
                int[] firstVisibleItems = null;
                firstVisibleItems = ((CatchStaggeredGridLayoutManager) rv.getLayoutManager()).findFirstVisibleItemPositions(firstVisibleItems);
                if (firstVisibleItems != null && firstVisibleItems.length > 0) {
                    pastVisiblesItems = firstVisibleItems[0];
                }
            }
            if (!posts.loading) {
                if ((visibleItemCount + pastVisiblesItems) + 5 >= totalItemCount && !posts.nomore) {
                    posts.loading = true;
                    posts.loadMore(adapter, id, false);
                }
            }
        }
    });
    return v;
}
Also used : CatchStaggeredGridLayoutManager(me.ccrama.redditslide.Views.CatchStaggeredGridLayoutManager) PreCachingLayoutManager(me.ccrama.redditslide.Views.PreCachingLayoutManager) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) SwipeRefreshLayout(androidx.swiperefreshlayout.widget.SwipeRefreshLayout) Profile(me.ccrama.redditslide.Activities.Profile) ContributionPosts(me.ccrama.redditslide.Adapters.ContributionPosts) ContributionPostsSaved(me.ccrama.redditslide.Adapters.ContributionPostsSaved) ContributionAdapter(me.ccrama.redditslide.Adapters.ContributionAdapter) RecyclerView(androidx.recyclerview.widget.RecyclerView) ToolbarScrollHideHandler(me.ccrama.redditslide.handler.ToolbarScrollHideHandler)

Aggregations

SwipeRefreshLayout (androidx.swiperefreshlayout.widget.SwipeRefreshLayout)41 RecyclerView (androidx.recyclerview.widget.RecyclerView)20 View (android.view.View)19 ToolbarScrollHideHandler (me.ccrama.redditslide.handler.ToolbarScrollHideHandler)10 Toolbar (androidx.appcompat.widget.Toolbar)9 FastScroller (eu.davidea.fastscroller.FastScroller)8 FlexibleItemDecoration (eu.davidea.flexibleadapter.common.FlexibleItemDecoration)8 CatchStaggeredGridLayoutManager (me.ccrama.redditslide.Views.CatchStaggeredGridLayoutManager)8 PreCachingLayoutManager (me.ccrama.redditslide.Views.PreCachingLayoutManager)8 DefaultItemAnimator (androidx.recyclerview.widget.DefaultItemAnimator)7 ExampleAdapter (eu.davidea.samples.flexibleadapter.ExampleAdapter)7 ScrollableUseCaseItem (eu.davidea.samples.flexibleadapter.items.ScrollableUseCaseItem)7 Bundle (android.os.Bundle)6 Intent (android.content.Intent)5 Handler (android.os.Handler)5 TextView (android.widget.TextView)5 ContributionAdapter (me.ccrama.redditslide.Adapters.ContributionAdapter)5 Context (android.content.Context)4 NonNull (androidx.annotation.NonNull)4 LinearLayoutManager (androidx.recyclerview.widget.LinearLayoutManager)4